You are on page 1of 94

JSF - KR Notes

KR Notes JavaServerFaces (JSF)


Introduction
Role of Servlets in Web Applications Evolution Servlets are java classes which reside and execute in an Application Server. They provide excellent support for web applications. But servlets were responsible both for content generation and presentation. This resulted in monolithic applications which were interspersed with a lot of html generation code. JSP as an Enhancement Java Server Pages (JSP) solved this issue in an elegant way. JSP Appliactions used special jsp tags for business logic and content generation. The html tags were used for the presentation part. Developing JSP pages was found to be easier, when compared to Servlet development. These jsp pages were translated and compiled to Servlets by the JSP engine and executed by the Servlet container.

Web Programming with Java

KR

JSF - KR Notes

Another important development in JSP was the provision of custom tags. Custom tags helped the developers to extend the functionality of the jsp pages, still hiding the code behind the custom tag. All of these contributed to the popularity of JSP. Even though JSP segregated processing from presentation, still both were part of the same page and hence are tightly coupled. When you want to modify of any of these components, it involves editing one or more jsp pages, leading to potential destabilization of a working system.

Struts to the Rescue Struts framework solved this problem by strictly adhering to Model View - Controller (MVC) architecture. It is similar to JSP development, but with a different methodology. A JSP file contains both business logic (enclosed in jsp tags) as well as presentation logic (with HTML tags). The navigation to other jsp pages, happens with the help of jsp:forward action, with the target jsp name being hard coded. As a result, all the presentation, processing and navigation components of the application are tightly bound. Struts decouples all the components and ensures smooth navigation to various jsp pages, through configuration files, which are in a way similar to web.xml. In Struts framework, the jsp pages handle only the display part.
Web Programming with Java KR

JSF - KR Notes

The business logic is handled by a java class. This class gets the user data entered in a jsp/html file, through a java bean. A master servlet , i.e., a controller servlet is responsible for managing all these activities. The Struts framework provides the necessary libraries in the form of packaged classes, which can be used by the developer to build a struts based Web application. Advantage JSF All the above technologies continued to concentrate on the processing part. The user interface part of the application never received the attention it deserved. On the user interface front, things were mostly left to HTML and its editors. Intgration with the user interface part was deficient, requiring the developer to write a lot of request processing code. JSF (Java Server Faces) technology helps the developers to address these issues. What is JSF JSF is a frame work similar to struts for development of web based applications. Like Struts, it also follows MVC design pattern. Managed Beans (POJOs) act as Model and take care of the processing part.
Web Programming with Java KR

JSF - KR Notes

JSF provides a powerful set of library of tags/classes for addressing the User Inteface part. These tags are used in jsp pages jsf enabled jsp pages. These pages constitute the view part. It provides a simple navigational model through a configuration file (XML). Supports even driven programming as in other languages. JSF makes use of the expression Language (EL) to bind the user interface elements to their respective bean fields. The Faces Servlet, as specified in web.xml, acts as the controller

First JSF Application ( jsfIntro )


This sample application illustrates the various stages of JSF development. It accepts the user name and location through a jsf-enabled-jsp and displays the same information through another jsf-enabledjsp page. The essential components of this jsf application are: welcomeJSF.jsp which accepts the input from the user A view component Jsfbean.java, also referred as Managed Bean, which stores the input data and is also responsible for processing Model Jsfhello.jsp, the output jsp, which displays the information to the user, as picked up from the Managed Bean.

Web Programming with Java

KR

JSF - KR Notes

web.xml , which configures the Faces Servlet as the controller servlet and also maps it to the url /faces/*. faces-config.xml which contains the details of your jsf application like managed bean class names,scope navigational information, etc., welcomeJSF.jsp Accepts input from the user Basically, a view component Includes the two standards jsf tag libraries jsf/core and jsf/html Uses the required attribute to make name field mandatory Uses the maxlength to fix the maximum enterable length Action attribute has a fixed string as its arguement It is mapped to an output jsp in faces-config.xml

<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" id="fname"/> Web Programming with Java KR <%--

JSF - KR Notes

6 <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :"

/></h2>

<h:inputText value="#{Jsfbean.location}"/> <h:commandButton value="Accept" action="accept"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

Jsfbean.java This acts as a Managed Bean Responsible for processing Plays the role of Model component
package jsf2; import import import import javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.validator.ValidatorException;

/** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { Web Programming with Java KR

JSF - KR Notes } return name;

public void setName(String name) { this.name = name; } }

jsfhello.jsp The output view Data for output are provided by the managed bean Includes the core libraries of jsf
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> </f:view> </body> </html>

web.xml Deployment descriptor for the Faces Servlet (Controller ) Describes the Faces Servlet class to the container Maps it to /faces/* url Default, provide by the IDE, mostly sufficient Needs no modification
KR

Web Programming with Java

JSF - KR Notes <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</paramname> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servletclass>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> Web Programming with Java KR

JSF - KR Notes

9 <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcomefile> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>javax.faces.FacesException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</excep tion-type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> KR

Web Programming with Java

JSF - KR Notes <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

10

faces-config.xml The connecting link between various components of our application. Provides Managed Bean details, navigation details, etc., to the Faces Servlet

<?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns /javaee http://java.sun.com/xml/ns/javaee/webfacesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-beanclass> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

Dynamic Navigation (jsf_from_action)


In the previous example, the action attribute of the CommandButton navigated to another jsp, jsfhello.jsp This is what we call static navigaton. Also, please note that the ManagedBean simply stored the input data and allowed it to be retrieved by the output jsp.
Web Programming with Java KR

JSF - KR Notes

11

It did not, per se, do any processing of business logic. But in jsf, the managed bean is also responsible for processing business logic. It can contain methods other than setters and getters. your action can then execute a method in your managed bean. The following example illustrates this feature. welcomejsf.jsp Accepts the username as an input text. Accepts location as a select item Command Buttons action attribute maps to a method in the managed bean.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" validator="#{Jsfbean.validateName} " id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> Web Programming with Java KR

JSF - KR Notes <h:selectOneMenu value="#{Jsfbean.location}"> <f:selectItem itemLabel="ASV SunTech" itemValue="ASV"/> <f:selectItem itemLabel="TechnoComplex" itemValue="TCO"/> <f:selectItem itemLabel="Siruseri Facility" itemValue="SRI"/> <f:selectItem itemLabel="Others" itemValue="NA"/> </h:selectOneMenu> <h:commandButton value="Accept" action="#{Jsfbean.Allocate}"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

12

Jsfbean.java Managed bean for our application Contains the Allocate() method, which is the value of the action attribute in the above jsp page.
package jsf2; import import import import javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.validator.ValidatorException;

/** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; public String getLocation() { return location; } Web Programming with Java KR

JSF - KR Notes public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void validateName(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { String vname = (String) value; if (vname.length() < 5) { FacesMessage message = new FacesMessage("name should be more than 5 characters"); throw new ValidatorException(message); } } public String Allocate() { String loc = getLocation(); String function = null; if (loc.equals("ASV")) { function = "TDV"; } else if (loc.equals("TCO")) { function = "DEV"; } else if (loc.equals("SRI")) { function = "TRN"; } else { function = "NA"; } System.err.println("returned " + function); return function; } }

13

ASV.jsp Output view Just displays a welcome messasge for the specified location
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

Web Programming with Java

KR

JSF - KR Notes <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

14

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> WELCOME TO SunTech - Training and Development </body> </html>

TCO.jsp Output view Just displays a welcome messasge for the specified location
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> WELCOME TO TCO - DEVELOPMENT </body> </html>

SRI.jsp Output view Just displays a welcome messasge for the specified location
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> Web Programming with Java

KR

JSF - KR Notes <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

15

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> WELCOME TO SIRUSERI ACADEMY - TRAINING </body> </html>

Web.xml Web deployment descriptor Default as provided by th ide Normally no change is required
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</paramname> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> Web Programming with Java KR

JSF - KR Notes

16 <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servletclass>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> Web Programming with Java KR

JSF - KR Notes file>

17 <welcome-file>faces/welcomeJSF.jsp</welcome-

</welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>javax.faces.FacesException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</excep tion-type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml JSF specific configuration file Provides the details of various jsf components like views, managed beans, navigation rules, etc., to the jsf controller Please note the inclusion of <from-action/> element in <navigation case/> This provides for the dynamic navigation, which is based on the outcome of a managed bean method.
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns /javaee http://java.sun.com/xml/ns/javaee/webfacesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> Web Programming with Java KR

JSF - KR Notes class> <managed-bean-class>jsf2.Jsfbean</managed-bean-

18

<managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-action>#{Jsfbean.Allocate}</from-action> <from-outcome>TDV</from-outcome> <to-view-id>/ASV.jsp</to-view-id> </navigation-case> <navigation-case> <from-action>#{Jsfbean.Allocate}</from-action> <from-outcome>DEV</from-outcome> <to-view-id>/TCO.jsp</to-view-id> </navigation-case> <navigation-case> <from-action>#{Jsfbean.Allocate}</from-action> <from-outcome>TRN</from-outcome> <to-view-id>/SRI.jsp</to-view-id> </navigation-case> <navigation-case> <from-action>#{Jsfbean.Allocate}</from-action> <from-outcome>NA</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

JSF Architecture
Now that we are through with two jsf applications up and running, its time for us to look into the Architecture of JSF. The instantiation of the managed beans, updating their properties with the request data, maintaining the session information, navigating to the required jsp, executing validations, displaying error messages, invoking the application, etc., are all being automatically taken care of by the jsf controller servlet Faces Servlet. All these activities right from receiving the client request till the dispatch of a final response fall into what is called Request Processing Lifecycle.

Web Programming with Java

KR

JSF - KR Notes

19

Basic Facts of JSF Provides a standard UI Component framework, containing classes for all user interface elements,events processing etc., Instantiates and maintains a component tree on the Server , which corresponds to the jsp view page displayed in the client. The component tree will have exclusive UI Component Objects, each representing every item text box, label, select menu, command button, etc., in your jsp page. An optional renderer class is responsible for client specific renderings of the UI components. Uses java beans as Model to store and process data and events. JSF implemets MVC Similar to Struts, JSF implements the Model View Controller (MVC) design pattern. The managed Bean which contains the processing data and business logic acts as the Model of the application. The View includes the jsp page, the UI components, the backing bean and the Renderer class. The Faces Servlet (javax.faces.webapp.FacesServlet) , acts as the Controller. JSF Request Processing Lifecycle The JSF Request Processing Lifecycle consists of the following phases: Restore View Apply Request Values Process Validations Update Model Values Invoke Application Render Response
KR

Web Programming with Java

JSF - KR Notes

20

Restore View When a new request (non post back) for a jsf enabled jsp page is received by the jsf controller, it creates a view containing the component tree in the server. In other words, an object is instantiated in memory corresponding to your jsp page. This view will have UI components representing each and every item in the specified jsp. If the request happens to be a post-back request, ie ., a page with request values being submitted, then the earlier view will be restored. The view thus created/ restored will be persisted in a container object called FacesContext. FacesContext is in a way similar to our ServletContext but will be specific for each request. This view (object representation of the view jsp ) should not be confused with your managed bean, which has got a different role.

Apply Request Values In this phase the request data ( name value pairs), received from the client is applied to the respective UI Component in the restored view. In the case of non-input fields, like the button or links, their current state i.e., whether clicked or not is recorded. Please note that no validations or conversions occur at this phase.

Process Validations Conversion and Validation of incoming data is carried out by jsf controller during this phase. When the jsp binds the value of a input field using EL as in
<h:inputText value="#{Jsfbean.age}" required="true"> Web Programming with Java KR

JSF - KR Notes <f:validateLongRange minimum=18 maximum=60/> </h:inputText>

21

the controller understands that the data need to be converted to an integer (based on its data type in the Jsfbean). Hence, the input string applied is now converted to an integer, in the UI component. Then the specified validations are carried out. Any user defined validation methods and conversion methods will also be invoked during this phase. If a component fails validation or conversion, its valid property will be set to false. The controller will also generate and queue up an error message for this validation failure. These messages will be displayed using <h:messages/> tag during the render response phase along with the input page.

Update Model Values This phase commences after the process validations phase. JSF will enter into this phase only after the validations and conversions are passed without errors in the previous phase. The validated and converted values will be applied to the respective bean properties during this phase. JSF controller will identify the correct bean properties based on the value bindings in the input jsp page.
e.g <h:inputText value="#{Jsfbean.age}" required="true"/>

Invoke Application After Update Model Values, JSF enters the Invoke Application phase. This is the phase where your business logic code is executed. Please remember that UI Components like Buttons, which implement ActionSource interface fire Action Events. They are associated with an action method or ActionListener method.
e.g

<h:commandButton value="Accept" action="accept"/>

These Action methods or ActionListener methods will be invoked during this phase. Further navigations based on action outcome are carried out during this phase.
KR

Web Programming with Java

JSF - KR Notes

22

Please note that ValueChange events are processed during Process Validations phase itself.

Render Response This happens to be the final phase of JSF Request Cycle. It is during this phase that the entire response is rendered to the client. The response could be rendered to different types of clients like Web Browsers, MobileDevices, etc, The rendered mark up will vary as html, wml, xml etc., based on the client. Also, this phase is responsible for persisting the current state of the View, so that it could be restored on subsequent web requests.

Using Custom Validation ( jsfValidation1 )


In addition to default validation as a part of tags attribute, line required, maxlength etc., it is also possible for you to define your custom validation routines. This example illustrates the use of custom validation. welcomeJSF.jsp Uses custom validation to validate the name field. Validation ensures that the entered name is always equal to or greater than five characters. The validator attribute has the name of the validation method in the managed bean, as its value.
<h:inputText value="#{Jsfbean.name}" required="true" validator="#{Jsfbean.validateName}"id="fname"/> <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. Web Programming with Java KR

JSF - KR Notes 23 --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" validator="#{Jsfbean.validateName}" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{Jsfbean.location}"/> <h:commandButton value="Accept" action="accept"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

Jsfbean.java Contains the custom validator method The name of the method could be anything. But the signature should be :
public void validateName(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException;

Creates a faces message and throws it as Validator Exception. <h:message/> tagt is responsible for the message display.
package jsf2; Web Programming with Java KR

JSF - KR Notes import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; /** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void validateName(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {

24

String vname = (String) value; if (vname.length() < 5) { FacesMessage message = new FacesMessage("name should be more than 5 characters"); throw new ValidatorException(message); } } }

jsfhello.jsp Output view Displays the name and location


<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> Web Programming with Java KR

JSF - KR Notes 25 <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> </f:view> </body> </html>

Web.xml Standard deployment descriptor as generated by the ide. Generally requires no modification.
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</paramname> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> Web Programming with Java KR

JSF - KR Notes

26 <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servletclass>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 Web Programming with Java KR

JSF - KR Notes

27 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcomefile> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>javax.faces.FacesException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</excep tion-type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml Configuration file for JSFApplication Contains Managaed Bean Description, Navigation information, etc.,
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns /javaee http://java.sun.com/xml/ns/javaee/webfacesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-beanclass> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> Web Programming with Java KR

JSF - KR Notes <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

28

Immediate Processing of Action Events ( jsfImmediateActionEvent )


Assume that after entering values in some fields, you want to hit the cancel button which navigates to a new jsp page (same page in our example). The Action Event associated with the cancel button will fire only during the Invoke Application phase. That means the other phases of the JSF Request processing Lifecycle get executed before that. So during the Process Validations phase, JSF will try to validate the fields and will throw error messages for failed validations. But your intention is to clear everything and start inputting in a fresh jsp and not correcting the existing input errors. This is achieved with the use of the immediate attribute.
<h:commandButton value="Cancel " action="cancel" immediate="true"/>

The immediate attribute ensures that the action event associated with the button is fired immediately, i.e., during the Apply Request Values phase ,itself. In other words, the event will fire before Process Validations phase. This will suppress any validations and enable you to navigate to a fresh page and start inputting values. welcomeJSF.jsp Includes a Cancel button whose action attribute navigates it to the same page, through an entry in faces-config.xml Any action associated with this event will fire during Invoke Application phase only.
Web Programming with Java KR

JSF - KR Notes

29

The Validation phase which will fire much before it, will attempt to validate the name field and throw an error message, in case of failed validation. To over come this, the immediate attribute of cancel is set to true for the CancelImmediate Button. Execute the application by clicking these buttons and observe the results.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" validator="#{Jsfbean.validateName }" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{Jsfbean.location}"/> <h:commandButton value="Accept" action="accept"/> <h:commandButton value="Cancel" action="cancel"/> <h:commandButton value="Cancel Immediate" action="cancel" immediate="true"/> Web Programming with Java KR

JSF - KR Notes </td> </tr> </table> </h:form> </body> </html> </f:view>

30

Jsfbean.java Managed bean of our application Contains the validation code for the name field
package jsf2; import import import import javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.validator.ValidatorException;

/** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void validateName(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { String vname = (String) value; if (vname.length() < 5) { Web Programming with Java KR

JSF - KR Notes FacesMessage message = new FacesMessage("name should be 5 or more than 5 characters"); throw new ValidatorException(message); } } }

31

Jsfhello.jsp The output view Displays the entered name and location
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> </f:view> </body> </html>

web.xml Deployment descriptor for the faces servlet Standard file created by the IDE.
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Web Programming with Java KR

JSF - KR Notes 32 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</paramname> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servletclass>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> Web Programming with Java KR

JSF - KR Notes 33 <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcomefile> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>javax.faces.FacesException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</excep tion-type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml JSF Configuration file


Web Programming with Java KR

JSF - KR Notes

34

Contains the descriptor details of Manged Beans, navigation details etc., Direct the cancel action to the same welcomeJSF.jsp

<?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns /javaee http://java.sun.com/xml/ns/javaee/webfacesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-beanclass> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>cancel</from-outcome> <to-view-id>/welcomeJSF.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

Immediate Processing of Validations( jsfImmediateValidations )


In the previous example, you learnt how to process Action events, immediately i.e., during the Apply Request Values Phase itself. This example will illustrate how to handle validations immediately. Also, you will learn how to peform look up validations and display the selected value immediately. welcomeJSF.jsp
Web Programming with Java KR

JSF - KR Notes

35

Performs the validation for name. Since the immediate attribute is set to true, the validation happens during the Apply Request Values phase itself. To submit this form without user involvement, we use the java script command:
<h:inputText value="#{Jsfbean.name}" required="true" immediate="true" onblur="this.form.submit();" validator="#{Jsfbean.validateName}" id="fname"/>

This, along with immediate attribute with value as true makes the validation execute immediately. The same technique is employed to validate the location and display the location name. In real life environments, there could be a database look up operation to fetch the name for the location.

<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr>
Web Programming with Java KR

JSF - KR Notes

36

<td> value="Your Name :" /></h2>

<h2><h:outputText

<h:inputText value="#{Jsfbean.name}" required="true" immediate="true" onblur="this.form.submit();" validator="#{Jsfbean.validateName}" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{Jsfbean.location}" validator="#{Jsfbean.validateLocation}" id="loc" immediate="true" onblur="this.form.submit()"/> <h:message for="loc"/> <h:outputText value="#{Jsfbean.locname}"/> <br/> <h:commandButton value="Accept" action="accept"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

ImmediateValidation.java Managed bean for our application Contains the validation methods for name and location The Validation method for location also displays the location name, if a valid location is entered. For invalid name or invalid location, an FacesMesssage object is created and an exception is thrown with that object. This message gets displayed with the help of <h:message/> Tag.
package jsf2; import import import import import javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.event.ValueChangeEvent; javax.faces.validator.ValidatorException; KR

Web Programming with Java

JSF - KR Notes /** * * @author 128117 */ public class ImmediateValidation { /** Creates a new instance of ImmediateValidation */ public ImmediateValidation() { super(); } private String name; private String location; private String locname; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocname() { return locname; } public void setLocname(String locname) { this.locname = locname; } public void validateName(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { String vname = (String) value; if (vname.length() < 5) { FacesMessage message = new FacesMessage("name should be more than 5 characters"); throw new ValidatorException(message); } } public void validateLocation(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { String loc = (String)value; if (loc.equals("ASV")) { locname = "SUNTECH"; Web Programming with Java

37

KR

JSF - KR Notes

38 } else { FacesMessage message = new FacesMessage("Invalid Location"); throw new ValidatorException(message); } } }

jsfhello.jsp The display output view. Gets displayed if all validations in the input page successfully pass the test.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> </f:view> </body> </html>

web.xml Standard Deployement Descriptor Created by the IDE as a default Need not be modified in most cases
<?xml version="1.0" encoding="UTF-8"?> Web Programming with Java KR

JSF - KR Notes 39 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</paramname> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servletclass>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> Web Programming with Java KR

JSF - KR Notes

40 <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcomefile> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>javax.faces.FacesException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</excep tion-type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

Web Programming with Java

KR

JSF - KR Notes

41

faces-config.xml JSF Configuration file Describes the various application components to the faces Servlet. Also provides navigational information.
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns /javaee http://java.sun.com/xml/ns/javaee/webfacesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-beanclass>jsf2.ImmediateValidation</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

Initializing Managed Bean Properties through Configuration File ( jsfInitManagedBean )


It is possible for us to provide intial values to the managed beans. We use the faces-config.xml to provide default values for the bean fields. welcomeJSF.jsp The input file to accept request data from the user Includes name, location and locationid as the input fields. Because of default initialization, these fields will be pre populated with default values.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> Web Programming with Java KR

JSF - KR Notes

42

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{Jsfbean.location}" id="loc"/> <h2><h:outputText value="Location ID :" /></h2> <h:inputText value="#{Jsfbean.locationid}" id="locid"/> <h:commandButton value="Accept" action="accept"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

Jsfbean.java The Managed bean Properties include name, location and locationid
package jsf2; Web Programming with Java KR

JSF - KR Notes import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; /** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; private int locationid; public int getLocationid() { return locationid; } public void setLocationid(int locationid) { this.locationid = locationid; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

43

Jsfhello.jsp The output jsp Valuebound to the managed bean fields


<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> Web Programming with Java KR

JSF - KR Notes 44 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> Your Location ID is <h1><h:outputText value="#{Jsfbean.locationid}" /></h1> </f:view> </body> </html>

web.xml Deployment descriptor for the Faces Servlet Default generated by the IDE Normally no need to modify
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param>

Web Programming with Java

KR

JSF - KR Notes

45 <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servletclass> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 Web Programming with Java KR

JSF - KR Notes 46 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcome-file> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>javax.faces.FacesException</exceptiontype> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</exception -type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml Faces configuration file Describes the bean, navigation etc., to the jsf controller Provides initial values to the bean properties
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/jav aee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>name</property-name> <value>Your Name</value> </managed-property> <managed-property> <property-name>location</property-name> Web Programming with Java KR

JSF - KR Notes <value>ASV</value> </managed-property> <managed-property> <property-name>locationid</property-name> <value>2</value> </managed-property> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

47

Initializing Managed Bean Properties through Request Parameters ( jsfParamManagedBean )


It is also possible to initialize the bean properties through Request Parameters. The Request Paramters could be passed as a part of the Query String This condition is speicified in the faces-config.xml. Picking up the cue from here, the JSF Controller initializes the bean properties using the request values, passes along with the query string. welcomeJSF.jsp The input jsp. The input fields will be prepopulated from the query parameters.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-Web Programming with Java KR

JSF - KR Notes 48 This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{Jsfbean.location}" id="loc"/> <h2><h:outputText value="Location ID :" /></h2> <h:inputText value="#{Jsfbean.locationid}" id="locid"/> <h:commandButton value="Accept" action="accept"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

Jsfbean.java The Managed Bean for our application. Contains name, location and location id as three properties.
package jsf2; import import import import /** * Web Programming with Java KR javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.validator.ValidatorException;

JSF - KR Notes * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; private int locationid; public int getLocationid() { return locationid; } public void setLocationid(int locationid) { this.locationid = locationid; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

49

jsfhello.jsp The output jsp page. Displays the input values


<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> Web Programming with Java KR

JSF - KR Notes 50 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> Your Location ID is <h1><h:outputText value="#{Jsfbean.locationid}" /></h1> </f:view> </body> </html>

web.xml Deployment Descriptor Default generated by the IDE Generally no need to modify.
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> Web Programming with Java KR

JSF - KR Notes

51 <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servletclass> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcome-file> Web Programming with Java KR

JSF - KR Notes 52 </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>javax.faces.FacesException</exceptiontype> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</exception -type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml Faces Configuration file Describes your faces application to the JSF Controller. Includes an element for receiving the parameters through query string.
<!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/jav aee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>name</property-name> <value>#{param.fname}</value> </managed-property> <managed-property> Web Programming with Java KR

JSF - KR Notes <property-name>location</property-name> <value>#{param.loc}</value> </managed-property> <managed-property> <property-name>locationid</property-name> <value>2</value> </managed-property> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

53

Note: The query string to be entered in the address bar of the browser will appear similar to the following one:

http://localhost:8084/jsfParamManagedBean/faces/welcomeJSF .jsp?fname=ganeshramsankar&&loc=ASV

Managed Bean and Scope


The scope of a managed bean needs to be specifed in facesconfig.xml. The possible values of scope are: request o The beans you create with request scope persist throughout the request duration. o In other words, they are accessible as long as the same request object is available. o Also, generally this is the preferred scope. session o The session scope makes the bean available throughout the session across the requests
Web Programming with Java KR

JSF - KR Notes

54

o The bean can be referred even if the request is new for the same client. application o A Managed bean defined with application scope can be accessed by multiple requests across different clients in the same application . none o Manged beans with scope as none are not instantiated by default. o Neither, are they stored in any particular scope. o They are instantiated only on demand by other managed beans. o Once instantiated, they persist as long as the calling bean is alive. o Once the calling bean returns (completes), this none scope bean, also ceases to exist. o This means, a subsequent call will result in the instantiation of a new bean again. Unlike jsp, there is NO page scope for a Managed Bean in jsf. Also please note that a managed bean can refer to another managed bean whose scope is o none o same as that of itself or o broader than itself The following example illustrates the behaviour of a bean with session scope: Managed Bean with Session Scope ( jsfBeanScope ) Illustrates the behaviour of a managed bean with session scope welcomeJSF.jsp
Web Programming with Java KR

JSF - KR Notes

55

The input jsp for our application Accepts the name and location The managed bean associated with this jsp is configured to be in session scope in faces-config.xml
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{Jsfbean.name}" required="true" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{Jsfbean.location}"/> <h:commandButton value="Accept" action="accept"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

Jsfbean.java
Web Programming with Java KR

JSF - KR Notes

56

Managed bean associated with this jsf application Scoped to session in faces-config.xml As such, it can be accesses across session Does not require the same request object to be present.

package jsf2; import import import import javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.validator.ValidatorException;

/** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

jsfhello.jsp The output view Displays the input values, name and location Accepts a value for seatno field Binds the value with bean2s seatno property.
KR

Web Programming with Java

JSF - KR Notes

57

Bean2 is another managed bean in the application.


<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <h:form> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> Enter Your Seat No.: <h:inputText value="#{Bean2.seatno}"/> <h:commandButton value="OK" action="ok"/> </h:form> </body> </html> </f:view>

Bean2.java Another managed bean in the application Contains the seatno property Value bound to the field in jsfhello.jsp
package jsf2; public class Bean2 { private String seatno; /** Creates a new instance of Bean2 */ public Bean2() { } public String getSeatno() { return seatno; } public void setSeatno(String seatno) { this.seatno = seatno; Web Programming with Java KR

JSF - KR Notes System.err.println("seat no "+seatno); } }

58

final.jsp The final output view. Displays the name, location and seatno. Please note that location and name fields have been value bound to the properties of Jsfbean. This is possible, because the scope of the Jsfbean has been set to session.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> Your Seat No is: <h1><h:outputText value="#{Bean2.seatno}" /></h1> <h1><h:outputText value="#{Jsfbean.name}" /></h1> <h1><h:outputText value="#{Jsfbean.location}"/></h1> Thank You </body> </html> </f:view>

web.xml Deployment Descriptor Describes the FacesServlet to the container. Performs Servlet mapping. Standard file generated by the IDE. Generally, no need to modify.
KR

Web Programming with Java

JSF - KR Notes

59

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servletclass> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> Web Programming with Java KR

JSF - KR Notes

60 <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcome-file> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>javax.faces.FacesException</exceptiontype> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</exception -type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

Web Programming with Java

KR

JSF - KR Notes

61

faces-config.xml JSF Configuration file. Describes the faces application, navigation and managed beans to the JSF Controller. Sets the scope of Jsfbean to session
<?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/jav aee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> <managed-bean> <managed-bean-name>Bean2</managed-bean-name> <managed-bean-class>jsf2.Bean2</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/jsfhello.jsp</from-view-id> <navigation-case> <from-outcome>ok</from-outcome> <to-view-id>/final.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

Note Change the scope from session to application. Invoke the application. Provide inputs to welcomeJSF.jsp and jsfhello.jsp Invoke the final.jsp separately as a separate request:
KR

http://localhost:8084/jsfBeanScope/faces/final.jsp Web Programming with Java

JSF - KR Notes

62

Observe that the name and location values are retained, thus maintaining application scope.

Backing Bean
Backing bean is a java class which represents all the User Interface (UI) objects in your jsf-enabled-jsp page. In otherwords, the backing bean will have members representing Buttons, Check Boxes, Input Fields, Output Fields, Labels etc.,
private HtmlInputText ppyn; private HtmlInputText ppno; private HtmlOutputText ppnolabel;

This is similar to what you would have seen in Visual Basic. Backing Bean Context and Usage When you want a field to be processed as a part of your business logic, you will include it as a property (field) in the managed bean. (e.g) Say you want to use the principal, rate of interest, period of loan to calculate the total amount payble, which in essesnce is a part of business logic, you will include it in a managed bean. But when your need is to respond to the user input immediately, or display another user interface item based on the data just entered, you will prefer a backing bean. (e.g) Say, if the user enters yes for Has Passport?, you want to display the Passport number input field, you will choose a backing bean instead. In short, the backing bean gives you excellent programmatic control over all the UI items.
Web Programming with Java KR

JSF - KR Notes

63

Many of the IDEs, create the backing bean for every jsf page by default. You may edit this and retain the required fields. Backing Bean Example ( jsfBackingBean ) Employs a backing bean for UI processing. Conditionally manipulates the UI Components. Managed Bean handles business code. welcomeJSF.jsp The input view of our application Contains input fields name, passport y/n, passport no. and location Renders the Passport No. field only if passport y/n is Y. This is achieved by manipulating the UI components in the backing bean.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> Web Programming with Java KR

JSF - KR Notes Name :" /></h2> required="true" <h2><h:outputText value="Your <h:inputText value="#{Jsfbean.name}"

64

:" /></h2>

id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Passport Y / N

<h:inputText binding="#{welcomeJSF_backing.ppyn}" required="true" id="pp" valueChangeListener="#{welcomeJSF_backing.disablePpno}" onchange="this.form.submit();"/> <br/> <h2><h:outputText value="Enter Passport No :" binding="#{welcomeJSF_backing.ppnolabel}" rendered="false"/></h2> <h:inputText binding="#{welcomeJSF_backing.ppno}" required="true" rendered="false" id="ppn"/> <br/> <h2><h:outputText value="Location (ASV / SRI / TCO ):" /></h2> <h:inputText value="#{Jsfbean.location}"/> <h:commandButton value="Accept" action="#{Jsfbean.AllotSeatNo}"/> </td> </tr> </table> </h:form> </body> </html> </f:view>

Value Binding Vs Instance Binding In the above welcomeJSF.jsp, please note that we have used binding=instead of value=, for Passport Y/N input text, PassportNo Label and passport No input text. This feature is called binding to an instance. In otherwords, you bind these fields to their respective instances of the components.

Web Programming with Java

KR

JSF - KR Notes

65

i.e the Passport No input text is bound to an instance of HtmlInputText ppno in our backing bean. Whereas, in value binding as in the case of name and location fields, the entered values are associated with the corresponding properties (fields) in the Managed bean as a string value. It is very important to remember that value binding happens during Update Model Values phase. But Instance binding occurs during Apply Request Values phase itself. welcomeJSF_backing.java The backing bean for our JSF Application Includes properties (fields) for representing the components which we want to be instance bound with the UI fields in the jsp .
private HtmlInputText ppyn; private HtmlInputText ppno; private HtmlOutputText ppnolabel;

disablePpno() invokes the various methods of the UI Components to render/ unrender these components conditionally in the view jsp. The convention requires the backing bean to be named by appending _backing to its input jsp and kept in a package named backing. Also it is a normal practice to provide one backing bean per input JSP page. We will discuss valueChangeEvent later under Listeners.
package backing; import javax.faces.component.html.HtmlInputText; import javax.faces.component.html.HtmlOutputText; import javax.faces.event.ValueChangeEvent; /** * * @author 128117 */ Web Programming with Java KR

JSF - KR Notes public class welcomeJSF_backing { /** Creates a new instance of welcomeJSF_backing */ public welcomeJSF_backing() { } private HtmlInputText ppyn; private HtmlInputText ppno; private HtmlOutputText ppnolabel; public HtmlInputText getPpno() { return ppno; } public void setPpno(HtmlInputText ppno) { this.ppno = ppno; } public HtmlInputText getPpyn() { return ppyn; } public void setPpyn(HtmlInputText ppyn) { this.ppyn = ppyn; } public HtmlOutputText getPpnolabel() { return ppnolabel; } public void setPpnolabel(HtmlOutputText ppnolabel) { this.ppnolabel = ppnolabel; }

66

public void disablePpno(ValueChangeEvent vce) { if (((String) (ppyn.getValue())).equals("N")) { ppno.setValue(""); // ppno.setDisabled(true); ppnolabel.setRendered(false); ppno.setRendered(false); } else if (((String) (ppyn.getValue())).equals("Y")) { //ppno.setDisabled(false); ppnolabel.setRendered(true); ppno.setRendered(true); } } }

Jsfbean Managed Bean Contains value bound fields


package jsf2; import javax.faces.application.FacesMessage; Web Programming with Java KR

JSF - KR Notes import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; /** * * @author 128117 */ public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; private String seatno; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSeatno() { return seatno; } public void setSeatno(String seatno) { this.seatno = seatno; } public String AllotSeatNo() { if (getLocation().equals("ASV")) { setSeatno("ASV001"); } else if (getLocation().equals("TCO")) { setSeatno("TCO001"); } else if (getLocation().equals("SRI")) { setSeatno("SRI001"); } else { setSeatno("GLOBAL"); } return "allocate"; } }

67

Web Programming with Java

KR

JSF - KR Notes

68

jsfhello.jsp The ouput view Provides the final outcome of the application
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> <h:form> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> Your Seat No is <h1><h:outputText value="#{Jsfbean.seatno}" /></h1> </h:form> </f:view> </body> </html>

web.xml Deployment Descriptor for the Faces Servlet. Defines the Servlet class. Peforms Servlet Mapping. Includes few other deployment info as required by the IDE. Default generated by the IDE. Normally doesnt require any modifications.

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> Web Programming with Java KR

JSF - KR Notes 69 <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servletclass> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servletclass>com.sun.webui.theme.ThemeServlet</servlet-class> Web Programming with Java KR

JSF - KR Notes 70 </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcome-file> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>javax.faces.FacesException</exceptiontype> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</exception -type> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml JSF Configuration file. Contains Managed Bean details. Includes Navigation details. Backing Bean details have also been included.
KR

Web Programming with Java

JSF - KR Notes

71

<?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/jav aee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>welcomeJSF_backing</managed-beanname> <managed-bean-class>backing.welcomeJSF_backing</managedbean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-action>#{Jsfbean.AllotSeatNo}</from-action> <from-outcome>allocate</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

JSF Event Managemnt

JSF being UI focussed by design, supports Event Driven programming model.

Events are generated when the user clicks a button or changes a value in a field. Actions and Listeners are specific methods of the managed bean, which could be associated with these events.

JSF Event model queues up these events as and when they occur.
KR

Web Programming with Java

JSF - KR Notes

72

This queuing up happens during Apply Request Values phase.

These events are processed during the appropriate phases depending upon the nature of the generated event.

In other words, at the end of the appropriate phase, JSF fires these events one by one chronologically. The associated Actions or Listeners which receive this notification execute the methods linked to these events. Also, when an event is generated - say button click, please be aware that nothing will happen immediately in the client. Instead, this will be stored in the event queue by th JSF Controller and will be handled by the Request Processiong Lifecycle at the appropriate phase for that event. Event Categories Events can be broadly classified into the following categories: Action Event Value Change Event Phase Event

Action Event
Action Events are generated by UI Components that initiate an action. Button component is an example. Action Events are normally processed at the end of the Invoke Application phase. Alternatively, if the immediate attribute has been set to true, they are processed at the end of the Apply request Values phase. All these components implement the ActionSource or ActionSource2 interface. Action events can be handled by Action Methods or Action Listener Methods.
Web Programming with Java KR

JSF - KR Notes

73

Use of Action Methods for handling Action Events


Action Methods are bound to action attribute.

Action Methods will take no arguments but return a String value. Also, action methods will be associated with navigarion In the welcomeJSF.jsp:
<h:commandButton value="Accept" action="#{Jsfbean.Allocate}"/>

In the Managed Bean Jsfbean.java:


public String Allocate() { String loc = getLocation(); String function = null; if (loc.equals("ASV")) { function = "TDV"; } else if (loc.equals("TCO")) { function = "DEV"; } else if (loc.equals("SRI")) { function = "TRN"; } else { function = "NA"; } System.err.println("returned " + function); return function; }

Use of Action Listener methods for Action Events When there is no need for navigation, we can use Action Listener Methods for responding to action events. Action Listener methods are bound to the actionlistener attribute of the UI component. Also, Action Listener methods will not return anything. The return type of an Action Listener method is always void. Instead, they accept an argument of type ActionEvent. In the welcomeJSF.jsp:
<h:commandButton value="Details" actionListener="#{Jsfbean.showDetails}"/> Web Programming with Java KR

JSF - KR Notes

74

In the Managed Bean Jsfbean.java:.


public void showDetails(ActionEvent ae){ String ltechtrack=getTechtrack(); System.err.println("tecktrack " + ltechtrack); if (ltechtrack.equals("AJ")){ setDetails("CoreJava, J2EE "); } else{ setDetails("ASP, ADO "); } }

Action Listener method for Action Events( jsfDefaultActionListener ) This application makes use of the default ActionListener method. The actionlistener attribute for the Details button in the welcomeJSF.jsp specifies showDetails() method as the listener method. showDetails() is defined in the Managed Bean of our application
<h:commandButton value="Details" actionListener="#{Jsfbean.showDetails}"/>

Clicking the above command button, invokes the showDetails() method.


<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Default Action Listener </title> </head> Web Programming with Java KR

JSF - KR Notes <body> <h:form> <table> <tr> <td> Name :" /></h2>

75

<h2><h:outputText value="Your

<h:inputText value="#{Jsfbean.name}" required="true"

id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText

value="Location :" /></h2>

<h:inputText value="#{Jsfbean.location}"/> <h2><h:outputText value="Technology Track :" /></h2> <h:selectOneMenu value="#{Jsfbean.techtrack}"> <f:selectItem itemLabel="Java" itemValue="AJ"/> <f:selectItem itemLabel="DotNet" itemValue="DN"/> </h:selectOneMenu> <h:commandButton value="Details" actionListener="#{Jsfbean.showDetails}"/> <h:outputText

value="#{Jsfbean.details}"/>

<h:commandButton value="Accept" action="accept"/> </td> </tr> </table>

</h:form> </body> </html> </f:view>

Jsfbean.java The managed bean for our application. Includes properties representing the fields in welcomeJSF.jsp
Web Programming with Java KR

JSF - KR Notes

76

Includes the listener method showDetails() associated with the action event for the command button labelled as Details. void showDetails(ActionEvent ae), accepts an Actionevent object as an arguement. Its return type is void. Listener methods cannot have a return type.
package jsf2; import javax.faces.event.ActionEvent; public class Jsfbean { /** Creates a new instance of Jsfbean */ public Jsfbean() { super(); } private String name; private String location; private String techtrack; private String details; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTechtrack() { return techtrack; } public void setTechtrack(String techtrack) { this.techtrack = techtrack; } public void showDetails(ActionEvent ae){ String ltechtrack=getTechtrack(); Web Programming with Java KR

JSF - KR Notes System.err.println("tecktrack " + ltechtrack); if (ltechtrack.equals("AJ")){ setDetails("CoreJava, J2EE "); } else{ setDetails("ASP, ADO "); } } }

77

jsfhello.jsp The output view. Displays the name and location as entered.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> </f:view> </body> </html>

web.xml The deployement descriptor. Describes the Faces Servlet and associated helper servlets to the container. Standard file generated by the IDE. Generally, need not be modified.
<?xml version="1.0" encoding="UTF-8"?> Web Programming with Java KR

JSF - KR Notes 78 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <filter> <filter-name>UploadFilter</filter-name> <filterclass>com.sun.webui.jsf.util.UploadFilter</filter-class> <init-param> <description>The maximum allowed upload size in bytes. If this is set to a negative value, there is no maximum. The default value is 1000000.</description> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <init-param> <description>The size (in bytes) of an uploaded file which, if it is exceeded, will cause the file to be written directly to disk instead of stored in memory. Files smaller than or equal to this size will be stored in memory. The default value is 4096.</description> <param-name>sizeThreshold</param-name> <param-value>4096</param-value> </init-param> </filter> <filter-mapping> <filter-name>UploadFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servletclass> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ExceptionHandlerServlet</servlet-name> <servletclass>com.sun.errorhandler.ExceptionHandler</servlet-class> <init-param> <param-name>errorHost</param-name> <param-value>localhost</param-value> </init-param> <init-param> <param-name>errorPort</param-name> <param-value>24444</param-value> </init-param> Web Programming with Java KR

JSF - KR Notes 79 </servlet> <servlet> <servlet-name>ThemeServlet</servlet-name> <servlet-class>com.sun.webui.theme.ThemeServlet</servletclass> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExceptionHandlerServlet</servlet-name> <url-pattern>/error/ExceptionHandler</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThemeServlet</servlet-name> <url-pattern>/theme/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcome-file> </welcome-file-list> <error-page> <exceptiontype>javax.servlet.ServletException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exception-type>javax.faces.FacesException</exceptiontype> <location>/error/ExceptionHandler</location> </error-page> <error-page> <exceptiontype>com.sun.rave.web.ui.appbase.ApplicationException</exceptiontype> <location>/error/ExceptionHandler</location> </error-page> <jsp-config> <jsp-property-group> <url-pattern>*.jspf</url-pattern> <is-xml>true</is-xml> </jsp-property-group> </jsp-config> </web-app>

faces-config.xml
Web Programming with Java KR

JSF - KR Notes

80

JSF Configuration file. Describes the Managed Bean, Navigation Details, etc., to the JSF Controller.
<?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://java.sun.com/xml/ns/java ee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>Jsfbean</managed-bean-name> <managed-bean-class>jsf2.Jsfbean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

Value Change Event


ValueChange Events are generated when the value of a UI component changes. These events are associated with UI Components like InputText, SelectBoxes, Selectmenus etc., A common feature across all these components is that all of them implement either the ValueHolder interface or the EditableValueHolder interface. ValueChange events are processed at the completion of the Process Validations phase of the Request Processing Lifecycle. On the other hand, if the immediate attribute has been set to true, then these events will be processed at the end of the Apply Request Values phase. ValueChange events are handled by ValueChangeListener methods.
Web Programming with Java KR

JSF - KR Notes

81

Value Change Listeners Value Change Listener methods are special methods defined in the managed bean. These methods accept ValueChangeEvent as an arguement. The return type of a ValueChangeListener method is always void.
public void showDetails(ValueChangeEvent vce){ String ltechtrack=(String) vce.getNewValue(); System.err.println("tt************* "+ ltechtrack); if (ltechtrack.equals("AJ")){ setDetails("CoreJava, J2EE "); } else{ setDetails("ASP, ADO "); } }

The UI is provided with a valueChangeListener attribute, whose value points to the corresponding listener method. It also specifies the immediate attribute as true, so that the listener event is processed at the end of Apply Request values phase itself. The javascript statement this.form.submit()ensures that this form is submitted without any specific user initiation.
<h:selectOneMenu value="#{Jsfbean.techtrack}" valueChangeListener="#{Jsfbean.showDetails}" immediate="true"onchange="this.form.submit();"> <f:selectItem itemLabel="Java" itemValue="AJ"/> <f:selectItem itemLabel="DotNet" itemValue="DN"/> </h:selectOneMenu>

It is also possible to develop your own custom Listener classes to handle value change events.

Value Change Listener Usage ( jsfDefaultValueChangeListener )


Web Programming with Java KR

JSF - KR Notes

82

Illustrates the use of default value change listener in a jsf application welcomeJSF.jsp The input view Accepts name and location as input text. Accepts technology track as a select box, associated with a valuechangelistener method. The attribute valueChangeListener specifies a method in managed bean as its listener method. The javascript statement this.form.submit()ensures that this form is submitted without any specific user initiation.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Default Action Listener </title> </head> <body> <h:form> <table> <tr> <td> Name :" /></h2> <h2><h:outputText value="Your

<h:inputText value="#{Jsfbean.name}" required="true"

id="fname"/> <br/> <h:message for="fname"/> <br/> KR

Web Programming with Java

JSF - KR Notes value="Location :" /></h2> <h2><h:outputText

83

<h:inputText value="#{Jsfbean.location}"/> <h2><h:outputText value="Technology Track :" /></h2> <h:selectOneMenu value="#{Jsfbean.techtrack}" valueChangeListener="#{Jsfbean.showDetails}" immediate="true"onchange="this.form.submit();"> <f:selectItem itemLabel="Java" itemValue="AJ"/> <f:selectItem itemLabel="DotNet" itemValue="DN"/> </h:selectOneMenu> <h:outputText <h:commandButton value="Accept" action="accept"/> </td> </tr> </table>

value="#{Jsfbean.details}"/>

</h:form> </body> </html> </f:view>

Jsfbeanval.java The managed bean for our JSF Application Represents the input fields name, location and techtrack as bean properties. Also includes as specific valueChangeListener method ShowDetails() for processing the value change event generated by the techtrack UI item. public void ShowDetails(ValueChangeEvent vce) accepts a ValueChangeEvent object as an argument. It does not return anything the return type is always void.
package jsf2; import javax.faces.event.ValueChangeEvent; public class Jsfbeanval { Web Programming with Java KR

JSF - KR Notes public Jsfbeanval() { super(); } private String name; private String location; private String techtrack; private String details; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTechtrack() { return techtrack; } public void setTechtrack(String techtrack) { this.techtrack = techtrack; } public void showDetails(ValueChangeEvent vce) { String ltechtrack = (String) vce.getNewValue(); System.err.println("tt************* " + ltechtrack); if (ltechtrack.equals("AJ")) { setDetails("CoreJava, J2EE "); } else { setDetails("ASP, ADO "); } } }

84

Jsfhello.jsp The output view


Web Programming with Java KR

JSF - KR Notes

85

Displays name and location as entered


<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{Jsfbean.name}" /></h1> Your Location is <h1><h:outputText value="#{Jsfbean.location}" /></h1> </f:view> </body> </html>

Data Conversion and Validation


Data Conversion ensures that the applications business logic deals with only the expected type of data. Validation ensures that such a data is validated as per the given constraints. JSF uses Converters for data conversion. Validation is handled by validators. Different Types of Conversion and Validation Iplicit Conversions Implicit Validations Standard Conversions Standard Validations Custom Conversions Custom Validations

Web Programming with Java

KR

JSF - KR Notes

86

Implicit Conversion Implicit converters convert the input data to the type expected by the properties of the bean to which these fields are bound. In the following example, JSF converts the request string to int based on the sno property of the managed bean.
<p>Enter Student No: <h:inputText value="#{jsfbean.sno}"id="stno"/>

But in the following case, no implicit conversion happens:


<p>Enter year: <h:inputText value2008 id="stno"/>

Implicit Validation Taken care of automatically by the Faces Validation System. When an attempt is made to convert and assign a wrong type to a field, the implicit validator fires automatically.

Standard Validators The JSF Validation system provides the following standard validator tags apart from the required attribute: <f:validate DoubleRange maximum=n1 minimum=n2/> <f:validate LongRange maximum=n1 minimum=n2/> <f:validate Length maximum=n1 minimum=n2/> <f:validate validator=methodname/> Standard Converters Apart from implicit conversion, the JSF conversion system provides the following standard conversion tags : <f:convertDateTime pattern=MM/dd/yy/> <f:convertNumber/> <f:converter=methodname/>

Data Conversion and Validation Example ( jsf_Conversion )


Illustrates some of the features of the JSF Conversion system.
Web Programming with Java KR

JSF - KR Notes

87

welcomeJSF.jsp Accepts the date in one format , converts and displays in a different format. Similarly formats the output number.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-This file is an entry point for JavaServer Faces application. --%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSF Page</title> </head> <body> <h:form> <table> <tr> <td> <h2><h:outputText value="Your Name :" /></h2> <h:inputText value="#{datacon.name}" required="true" validator="#{datacon.val idateName}" id="fname"/> <br/> <h:message for="fname"/> <br/> <h2><h:outputText value="Location :" /></h2> <h:inputText value="#{datacon.location}"/> /></h2> <h2><h:outputText value="Amount :"

<h:inputText value="#{datacon.percentmarks}"/> <h2><h:outputText value="Date of Joining :" /></h2> <h:inputText value="#{datacon.doj}" id=doj> Web Programming with Java KR

JSF - KR Notes yyyy"/> <h:message for = doj/> action="accept"/> <f:convertDateTime pattern="dd-MM</h:inputText>(dd-mm-yyyy) <br/> <h:commandButton value="Accept" </td> </tr> </table>

88

</h:form> </body> </html> </f:view>

DataConversion.java The managed bean for our application. Contains a custom Validator method
package dc; import import import import import java.util.Date; javax.faces.application.FacesMessage; javax.faces.component.UIComponent; javax.faces.context.FacesContext; javax.faces.validator.ValidatorException;

public class DataConversion { /** Creates a new instance of Jsfbean */ public DataConversion() { super(); } private String name; private String location; private Double percentmarks; private Date doj; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; Web Programming with Java KR

JSF - KR Notes } public Double getPercentmarks() { return percentmarks; } public void setPercentmarks(Double percentmarks) { this.percentmarks = percentmarks; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; }

89

public void validateName(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { String vname = (String) value; if (vname.length() < 5) { FacesMessage message = new FacesMessage("name should be more than 5 characters"); throw new ValidatorException(message); } } }

jsfhello.jsp The output view. Displays the date in the specified format. Formats and displays the amount already input.
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> Web Programming with Java KR

JSF - KR Notes 90 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP jsfPage</title> </head> <body> <f:view> Welcome <h1><h:outputText value="#{datacon.name}" /></h1> Your Location is <h1><h:outputText value="#{datacon.location}" /></h1> <h1><h:outputText value="#{datacon.percentmarks}"> <f:convertNumber pattern="INR ##,###.00" /> </h:outputText> </h1> <h1> EEEE ',' yyyy"/>

<h:outputText value="#{datacon.doj}"> <f:convertDateTime pattern="dd',' MMMM ','

</h:outputText> </h1> </f:view> </body> </html>

web.xml Deployment Descriptor. Default as provided by the IDE. Generally no need to modify.
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param> <param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</paramname> <param-value>client</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> Web Programming with Java KR

JSF - KR Notes <servletclass>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/welcomeJSF.jsp</welcome-file> </welcome-file-list> </web-app>

91

faces-config.xml JSF Configuration file. Describes the managed bean to the JSF Controller Servlet. Includes navigation details.
<?xml version='1.0' encoding='UTF-8'?> <!-- =========== FULL CONFIGURATION FILE ================================== --> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> <managed-bean> <managed-bean-name>datacon</managed-bean-name> <managed-bean-class>dc.DataConversion</managed-beanclass> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <navigation-rule> <from-view-id>/welcomeJSF.jsp</from-view-id> <navigation-case> <from-outcome>accept</from-outcome> <to-view-id>/jsfhello.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>

Web Programming with Java

KR

JSF - KR Notes

92

Jsf- Core Component Library


The jsf-core includes the following tags:

actionListener attribute convertDateTime converter convertNumber facet loadBundle param selectItem selectItems subview validateDoubleRange validateLength validateLongRange validator valueChangeListener verbatim view

Jsf- HTML Component Library


The jsf-html component library includes the following tags: column commandButton
KR

Web Programming with Java

JSF - KR Notes

93

commandLink dataTable form graphicImage inputHidden inputSecret inputText inputTextarea message messages outputFormat outputLabel outputLink outputText panelGrid panelGroup selectBooleanCheckbox selectManyCheckbox selectManyListbox selectManyMenu selectOneListbox selectOneMenu selectOneRadio

Web Programming with Java

KR

JSF - KR Notes

94

Web Programming with Java

KR