Chapter 11 © 2009 by Addison Wesley Longman, Inc. 1 11.1 Introduction to Servlets - A servlet is a compiled Java class - Servlets are executed on the server.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

JSP and Servelets.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Internet Technologies 1 Master of Information System Management Java Server Faces Model/View/Controller Design Pattern for Web Development Slides.
An introduction to Java Servlet Programming
Chapter 11 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 11 Sebesta: Programming the World Wide Web.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
Web programming for project students Dr Jim Briggs.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
UNIT-V The MVC architecture and Struts Framework.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
CSCI 6962: Server-side Design and Programming Course Introduction and Overview.
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
Chapter 11 © 2005 by Addison Wesley Longman, Inc Overview of Servlets - A servlet is a compiled Java class - Servlets are executed on the server.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Chapter 11 © 2010 by Addison Wesley Longman, Inc Introduction to Servlets - A servlet is a Java object that responds to HTTP requests and is executed.
Chapter 11 © 2014 by Pearson Education Introduction to Servlets - A servlet is a Java object that responds to HTTP requests and is executed on a.
JSP Java Server Pages Softsmith Infotech.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
CSCI 6962: Server-side Design and Programming Introduction to Java Server Faces.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
Mark Dixon 1 12 – Java Beans. Mark Dixon 2 Session Aims & Objectives Aims –To cover the use of Java Beans Objectives, by end of this week’s sessions,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Web App GUI: JSP Basics & Forms 3680 Enterprise Programming.
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
Chapter 11 © 2003 by Addison Wesley Longman, Inc. 1 Chapter 11 Introduction to Web Servers and Servlets.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
Java Servlets References: Karen Anewalt, Mary Washington College.
11.1 Introduction to Servlets
11.1 Web Server Operation - Client-server systems
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Presentation transcript:

Chapter 11 © 2009 by Addison Wesley Longman, Inc Introduction to Servlets - A servlet is a compiled Java class - Servlets are executed on the server system under the control of the Web server - Servlets are managed by the servlet container, or servlet engine - Servlets are called through HTML - Servlets receive requests and return responses, both of which are supported by the HTTP protocol - When the Web server receives a request that is for a servlet, the request is passed to the servlet container - The container makes sure the servlet is loaded and calls it - The servlet call has two parameter objects, one with the request and one for the response - When the servlet is finished, the container reinitializes itself and returns control to the Web server

Chapter 11 © 2009 by Addison Wesley Longman, Inc Introduction to Servlets (continued) - Servlet uses: 1. to dynamically generate responses to browser requests 2) as alternatives to Apache modules - All servlets are classes that either implement the Servlet interface or extend a class that implements the Servlet interface - The Servlet interface provides the interfaces for the methods that manage servlets and their interactions with clients - Most user-written servlet classes are extensions to HttpServlet (which is an extension of GenericServlet, which implements the Servlet Interface)

Chapter 11 © 2009 by Addison Wesley Longman, Inc Introduction to Servlets (continued) - Two other necessary interfaces: - ServletResponse – to encapsulate the communications, client to server - ServletRequest – to encapsulate the communications, server to client - Provides servlet access to ServletOutputStream - HttpServlet – an abstract class - Extends GenericServlet - Every subclass of HttpServlet MUST override at least one of the methods of HttpServlet doGet doPost doPut doDelete All of these are called by the server

Chapter 11 © 2009 by Addison Wesley Longman, Inc Introduction to Servlets (continued) - The protocol of doGet is: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException - ServletException is thrown if the GET request could not be handled - The protocol of doPost is similar - Servlet output – HTML 1. Use the setContentType method of the response object to set the content type to text/html response.setContentType("text/html"); 2. Create a PrintWriter object with the getWriter method of the response object PrintWriter servletOut = response.getWriter();

Chapter 11 © 2009 by Addison Wesley Longman, Inc Introduction to Servlets (continued) - Example – Respond to a GET request with no data  SHOW tst_greet.html and Greeting.java - Servlet Containers - Apache Tomcat - GlassFish – an application server for J2EE

Chapter 11 © 2009 by Addison Wesley Longman, Inc NetBeans - Prior to Servlet 2.2 spec in 2003, building servlet applications was relatively simple – use Tomcat - Deployment became far more complex when other servlet containers appeared - In response, a standard way to deploy servlet applications was developed – WAR files - The structure of a WAR file is too complex to do by hand, so many developers now use a framework - NetBeans Initial screen:  SHOW Figure New Project screen:  SHOW Figure New Web Application screen:  SHOW Figure 11.5

Chapter 11 © 2009 by Addison Wesley Longman, Inc NetBeans (continued) - Enter a project name and click Next - Brings up the Server and Settings screen - Click Finish to get the workspace with a skeletal version of the initial markup document ( index.jsp )  SHOW Figure Edit index.jsp to have the body of tstGreet.html - The modified document can be cleaned up by selecting Source/Format - Save it by selecting File/Save - Verify its display with Build/Build Main Project and Run/Run Main Project - To create the servlet, right click the project name and select New/Servlet, which produces the New Servlet screen  SHOW Figure Enter the name of the servlet, Greeting and click Finish

Chapter 11 © 2009 by Addison Wesley Longman, Inc NetBeans (continued)  SHOW the servlet produced by NetBeans - This is a standard template from NetBeans - Includes four methods - A try / finally block is included, but often not needed - The standard template can be modified - To get what we want, we place the central parts of the Greeting.java class into the processRequest method - Then we delete some unnecessary comments and getServletInfo  SHOW the completed Greeting.java - If we build and run the project, we get the same output as with the non-NetBeans version - For this trivial application, NetBeans created 14 directories and 19 files

Chapter 11 © 2009 by Addison Wesley Longman, Inc A Survey Example - An Example – a survey of potential purchases of consumer electronics products  SHOW index.jsp for Survey and its display - The servlet: - To accumulate voting totals, it must write a file on the server - The file will be read and written as an object (the array of vote totals) using ObjectInputStream - An object of this class is created with its constructor, passing an object of class FileInputStream, whose constructor is called with the file variable name as a parameter ObjectInputStream indat = new ObjectInputStream( new FileInputStream( File_variable_name )); - On input, the contents of the file will be cast to integer array

Chapter 11 © 2009 by Addison Wesley Longman, Inc A Survey Example (continued) - The servlet must access the form data from the client - This is done with the getParameter method of the request object, passing a literal string with the name of the form element e.g., if the form has an element named zip zip = request.getParameter("zip"); - If an element has no value and its value is requested by getParameter, the returned value is null - If a form value is not a string, the returned string must be parsed to get the value - e.g., suppose the value is an integer literal - A string that contains an integer literal can be converted to an integer with the parseInt method of the wrapper class for int, Integer price = Integer.parseInt( request.getParameter("price"));

Chapter 11 © 2009 by Addison Wesley Longman, Inc A Survey Example (continued) - The file structure is an array of 14 integers, 7 votes for females and 7 votes for males - Servlet actions: If the votes data array exists read the votes array from the data file else create the votes array Get the gender form value Get the form value for the new vote and convert it to an integer Add the vote to the votes array Write the votes array to the votes file Produce the return XHTML document that shows the current results of the survey - Every voter will get the current totals  Show the servlet, Survey.java

Chapter 11 © 2009 by Addison Wesley Longman, Inc A Survey Example (continued)

Chapter 11 © 2009 by Addison Wesley Longman, Inc Storing Information about Clients - A session is the collection of all of the requests made by a particular browser to a particular server from the time the browser is started until the user exits the browser - The HTTP protocol is stateless - But, there are several reasons why it is useful for the server to relate a request to a session - Shopping carts for many different simultaneous customers - Customer profiling for advertising - Customized interfaces for specific clients - Approaches to storing client information: - Store it on the server – too much to store! - Store it on the client machine - this works - Cookies - A cookie is an object sent between the server and the client

Chapter 11 © 2009 by Addison Wesley Longman, Inc Storing Information about Clients (continued) - Every HTTP communication between the browser and the server includes information in its header about the message - At the time a cookie is created, it is given a lifetime - Every time the browser sends a request to the server that created the cookie, while the cookie is still alive, the cookie is included - A browser can be set to reject all cookies - A cookie object has data members and methods - Data members to store lifetime, name, and a value (the cookies’ value) - Methods: setComment, setMaxAge, setValue, getMaxAge, getName, and getValue - Cookies are created with the Cookie constructor Cookie newCookie = new Cookie(gender, vote);

Chapter 11 © 2009 by Addison Wesley Longman, Inc Storing Information about Clients (continued) - By default, a cookie’s lifetime is the current session - If you want it to be longer, use setMaxAge - A cookie is attached to the response with addCookie - Order in which the response must be built: 1. Add cookies 2. Set content type 3. Get response output stream 4. Place info in the response - The browser does nothing with cookies, other than storing them and passing them back - A servlet gets a cookie from the browser with the getCookies method Cookie theCookies []; … theCookies = request.getCookies(); - A Vote Counting Example  Show index.jsp for VoteCounter

Chapter 11 © 2009 by Addison Wesley Longman, Inc Storing Information about Clients (continued) - Vote counting servlet algorithm: If the form does not have a vote return a message to the client – “No vote” else If the client did not vote before If the votes data file exists read in the current votes array else create the votes array end if update the votes array with the new vote write the votes array to disk return a message to the client, including totals else return a message to the client – “Illegal vote” end if

Chapter 11 © 2009 by Addison Wesley Longman, Inc Storing Information about Clients (continued) - The servlet uses two utility methods: 1. A predicate method that determines whether the client has already voted 2. A method to create the XHTML header text  Show VoteCounter.java - No vote: - Voted before: - Legal vote:

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages - Motivation - Servlets require mixing of XHTML into Java - JSP mixes code into XHTML, although the code can be in a separate file - Servlets are more appropriate when most of the document to be returned is dynamically generated - JSP is more appropriate when most of the document to be returned is predefined - JSP Documents (using classic (not XML) syntax) - Are converted to servlets by the JSP container - Consist of four different kinds of elements: 1. Directives – messages to the JSP container 2. XHTML or XML markup – called template text - The static part of the document 3. Action elements 4. Scriptlets

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages (continued) - Action elements - Dynamically create content - The output of a JSP document is a combination of its template text and the output of its action elements - Appear in three different categories: 1. Standard – defined by the JSP spec; limited scope and value 2. Custom – defined by an organization for their particular needs 3. JSP Standard Tag Library (JSTL) – created to meet the frequent needs not met by the standard action elements - Consists of five libraries - Differences between JSTL action elements and a programming language: 1. The syntax is different 2. Action elements are much easier to use than a programming language

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages (continued) - Directives - Tags that use delimiters - The most common directives are page and taglib - page is used to specify attributes, such as contentType - taglib is used to specify a library of action elements taglib prefix = ″c″ uri = ″ %> - JSP Expression Language - Similar to the expressions of JavaScript - For example, arithmetic between a string and a number - Has no control statements - Syntax: ${ expression }

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages (continued) - JSP Expression Language (continued) - Consist of literals, arithmetic operators, implicit variables (for form data), and normal variables - EL is used to set the attribute values of action elements (always strings) - EL data often comes from forms - The implicit variable, param, stores a collection of all form data values ${param.address} - If the form data name has special characters: ${param[′cust-address′]} - Another implicit variable: pageContext - Has lots of info about the request e.g., contentType, contentLength, remoteAddr

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages (continued) - JSP Expression Language (continued) - Output is usually created with out - Example – convert Celsius temperatures to Fahrenheit (tempConvertEL) - Need a form to get the Celsius temperature from the user  SHOW index.jsp for tempConvertEL2 - A second document is used to perform the conversion and display the result - The conversion is done using EL  SHOW tempConvertEL2.jsp

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages (continued) - JSTL Control Action Elements - Flow control elements – the Core library of JSTL - Selection – if element - Often used to choose whether it is the first call of a combined document <c:if test = ″${pageContext.request.method == ′POST′}″> … - This selector can be used to build the temperature conversion application with a single document  SHOW tempconvertEL1.jsp - Loops – forEach element (an iterator) - Often used for checkboxes and menus to determine the values of the parts - The paramValues implicit variable has an array of the values in checkboxes and menus

Chapter 11 © 2009 by Addison Wesley Longman, Inc Java Server Pages (continued) - JSTL Control Action Elements (continued) - forEach has two attributes, items and var, which get the specific item and its value - If we had a collection of checkboxes named topping <c:forEach items = ″${paramValues.topping}″ var = ″top″> - forEach can also be used for counting loops … - The choose element – to build switch constructs - choose, which has no attributes, uses two other elements, when and otherwise - when has the test attribute, which has the control expression - Radio buttons require a switch construct  SHOW index.jsp for the radioButtons app

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaBeans - The JavaBeans architecture provides a set of rules for building a special category of Java classes that are designed to be a reusable stand-alone software components called beans - Rigid naming conventions are required to allow builder tools to determine the methods and data of a bean class - All bean data that is to be exposed must have getter and setter methods whose names must begin with “get” and “set”, respectively - The rest of the getter and setter names must be the data variable’s name - In JSP, beans are used as containers for data - They are usually built with a framework - The contained data are called properties - Property names must begin with lowercase letters

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaBeans (continued) - The JSP standard element creates instances of a bean - Requires two parameters: id and class - The value of id is a reference to the bean instance - The value of class is a package name and the class name, catenated with a period e.g., to create an instance of the bean class named Converter, which is defined in the package org.mypackage.convert, use: <jsp:useBean id = ″mybean″ class = ″org.mypackage.convert.Converter″ /> - Bean instances differ from Java objects in that they have different purposes and uses - Java objects are created and used by Java programs - Bean instances are created and used by JSP documents (no programming)

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaBeans (continued) - There are two other standard action elements for dealing with beans - sets a property value in a bean <jsp:setProperty name = ″mybean″ property = ″sum″ value = ″100″ /> - Often need to move values from a form component to a bean property <jsp:setProperty name = ″mybean″ property = ″zip″ param = ″zipcode″ /> - If the form component and the property have the same name, the param attribute is not required - All JSP values and all form component values are strings - If a bean property is not a string and is assigned a form component value, the value is implicitly converted to the type of the property

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaBeans (continued) - fetches a property value from a bean - Takes two attributes, name and property <jsp:setProperty name = ″mybean″ property = ″sum″ /> - EL can be used to fetch a property from a bean ${mybean.sum} - Example – temperature conversion, again - Project name: tempConvertB  SHOW index.jsp for tempConvertB - The response document ( response.jsp ) - Name the package org.mypackage.convert and the class name Converter  SHOW response.jsp for tempConvertB

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaBeans (continued) - Finally, the bean class - Right click on the project in the Projects list - Select New/Java class - Name the class Converter and the package org.mypackage.convert - Type the bean into the workspace  SHOW Converter.java

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces - Another layer on the JSP technology - Provides an event-driven user interface programming model - Included in J2EE - Client-generated events can be connected to server-side application code - User interfaces can be constructed with reusable and extensible components - User interface state can be saved and restored beyond the life of the server request - JSF allows: 1. managing the state of components 2. processing component values 3. validating user input 4. handling user interface events - JSF uses beans to store and manipulate the values of components

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - Tag Libraries for JSF: - Core Tags and HTML Tags – a total of 45 tags - Most JSF documents use both - Directives to gain access to the libraries: prefix="f" uri=" prefix="h" uri=" uri=" - We’ll only use one Core tag, view - We’ll use three HTML tags, form, outputText, and inputText - form is used to provide a container for the user interface components - outputText is used to display text or bean properties - For literals, the literal is assigned to the value attribute - For bean properties, a JSF expression is used

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - JSF expressions are similar to EL expressions, except that # is used instead of $ - inputText is used to specify a text box for user input - In most cases, the value is bound to a bean property, using the value attribute - The onChange attribute is used to specify a JavaScript handler when the component loses focus and its value has been changed since it gained focus - The valueChangeListener is used for event handling

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - A skeletal JSF document: prefix="f" uri=" prefix="h" uri=" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - JSF Event Handling - Similar to GUIs with Java - Events are defined by classes - There are three categories of events in JSF: value-change, action, and data-model (phase) - Value-change events are raised with the value of a component is changed - Action events are raised when a button is clicked or a hyperlink is activated - There are two ways to handle JSF events: 1. Implement an event listener interface and register it on the component by nesting a valueChangeListener element or an actionListener element inside the component element 2. Implement a method in the bean of the document that contains the component to handle the event - Such a method is referenced with a method- binding JSF expression in an attribute of the component’s tag

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - A class that implements ValueChangeListener must implement the processValueChange method, whose parameter is the event - The class of the event is ValueChangeEvent - A class that implements ActionListener must implement the processAction method, whose parameter is the event - In this case, the class of the event is ActionEvent - The event objects have both the old and new values of the component that raised the event - The values can be obtained with the getNewValue and getOldValue methods on the event object - Neither takes a parameter public class TempChanged extends Object implements ValueChangeListener { public void processValueChange( ValueChangeEvent event) throws AbortProcessingException {... }... }

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - The attribute of the component element on which is registered the listener and the nested element in the component element have the same name - For action events, it is valueChangeListener - For the handler in the bean: <h:inputText... valueChangeListener = "#{MyBean.fixit}" /> - For the handler as an implementation of a listener interface: <h:inputText... - An Example – the same one… tempConvertF - The conversion will be done by an event handler when the text box that gets the Celsius temperature loses focus - We use the JavaServer Faces framework of NetBeans

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> JSP Page

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - Next, add the user interface to the skeletal document Welcome to the temperature converter Enter a temperature in Celsius: <h:inputText size = "4" value = "#{UserBean.celsius}" onchange = "submit()" valueChangeListener = "#{UserBean.convert}" /> The equivalent temperature in Fahrenheit: <h:outputText value = "#{UserBean.fahrenheit}" />

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) /** * UserBean.java * (documentation) */ import javax.faces.event.ValueChangeEvent; public class UserBean { private String celsius; private String fahrenheit; /** Creates a new instance of UserBean */ public UserBean() { celsius = null; fahrenheit = null; } public void setCelsius(String celsius) { this.celsius = celsius; } public String getCelsius() { return celsius; } public void setFahrenheit(String fahrenheit) { this.fahrenheit = fahrenheit; } public String getFahrenheit() { return fahrenheit; } public String convert(ValueChangeEvent event){ celsius = (String) event.getNewValue(); fahrenheit = Float.toString(1.8f * Integer.parseInt(celsius) f); return fahrenheit; }

Chapter 11 © 2009 by Addison Wesley Longman, Inc JavaServer Faces (continued) - The initial screen: - The result screen: