2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology JavaServer Faces Technology User Interface JavaServer Faces Technology Benefits What Is a JavaServer Faces Application? A Simple JavaServer Faces Application Steps in the Development Process Mapping theFacesServlet Instance User Interface Component Model User Interface Component Classes Using the Unified EL to Reference Backing Beans The Life Cycle of a JavaServer Faces Page Further Information about JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | A Simple JavaServer Faces ApplicationThis section describes the general steps involved in developing a simple JavaServer Facesapplication from the perspective of different development roles. These roles are:
This application is quite simple, and so it does not include anycustom components. See chapterWriting a Method to Handle a Value-Change Event to learn about the responsibilities of a component writer. Steps in the Development ProcessDeveloping a simple JavaServer Faces application usually requires these tasks:
The example used in this section is theguessNumber application, located in thetut-install/javaeetutorial5/examples/web/ directory. It asks you to guess a number between 0 and 10,inclusive. The second page tells you whether you guessed correctly. The example alsochecks the validity of your input. The system log prints Duke’s number.Figure 10-2shows what the first page looks like. Figure 10-2 Thegreeting.jsp Page of theguessNumber Application ![]() The source for theguessNumber application is located in thetut-install/javaeetutorial5/examples/web/guessNumber/ directory created whenyou unzip the tutorial bundle (seeChapter 2, Using the Tutorial Examples). To build, package, deploy, and run this example using NetBeans IDE, follow thesesteps:
To build, package, and deploy this example using Ant, follow these steps:
To learn how to configure the example, refer to the deployment descriptor (theweb.xml file), which includes the following configurations:
Mapping theFacesServlet InstanceAll JavaServer Faces applications must include a mapping to theFacesServlet instancein their deployment descriptors. TheFacesServlet instance accepts incoming requests, passes them tothe life cycle for processing, and initializes resources. The following piece of theguessNumber example’s deployment descriptor performs the mapping to theFacesServlet instance: <servlet> <display-name>FacesServlet</display-name> <servlet-name>FacesServlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet </servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>FacesServlet</servlet-name> <url-pattern>/guess/*</url-pattern></servlet-mapping> The mapping toFacesServlet shown above uses a prefix mapping to identify aJSP page as having JavaServer Faces components. Because of this, the URL tothe first JSP page of the application must include the mapping. To accomplishthis, theguessNumber example includes an HTML page that has the URL tothe first JSP page: <a href="guess/greeting.jsp"> SeeIdentifying the Servlet for Life Cycle Processing for more information on how to map theFacesServlet instance. Creating the PagesCreating the pages is the page author’s responsibility. This task involves laying outUI components on the pages, mapping the components to beans, and adding tagsthat register converters, validators, or listeners onto the components. In this section you will build thetut-install/javaeetutorial5/examples/examples/web/guessNumber/web/greeting.jsp page, the first pageof theguessNumber application. As with any JSP page, you’ll need to addthe usual HTML and HEAD tags to the page: <HTML xmlns="http://www.w3.org/1999/xhtml"xml:lang="en"> <HEAD> <title>Hello</title> </HEAD> ...</HTML> You’ll also need a page directive that specifies the content type: <%@ page contentType="application/xhtml+xml" %> Declaring the Tag LibrariesIn order to use JavaServer Faces components in JSP pages, you needto give your pages access to the two standard tag libraries, the HTMLcomponent tag library and the core tag library usingtaglib declarations: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http:.//java.sun.com/jsf/core" prefix="f" %> The first taglib declaration declares the HTML component tag library with a prefix,h. All component tags in the page have this prefix. The core taglibrary is declared with the prefixf. All core tags in the pagehave this prefix. User Interface Component Model includes a table that lists all the component tags included with JavaServerFaces technology.Adding UI Components to a Page Using the HTML Component Tags discusses the tags in more detail. Adding theview andform TagsAll JavaServer Faces pages are represented by a tree of components, called aview. Theview tag represents the root of the view. All JavaServer Facescomponent tags must be inside of aview tag, which is defined inthe core tag library. Theform tag represents an input form component, which allows the user toinput some data and submit it to the server, usually by clicking abutton. All UI component tags that represent editable components (such as text fieldsand menus) must be nested inside theform tag. In the case ofthegreeting.jsp page, some of the tags contained in the form areoutputText,inputText,commandButton, andmessage. You can specify an ID for the form tag.This ID maps to the associated form UI component on the server. With theview andform tags added, our page looks like this (minusthe HTML and HEAD tags): <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> </h:form></f:view> Adding a Label ComponentTheoutputText tag represents a label. Thegreeting.jsp page has twooutputTexttags. One of the tags displays the number 0. The other tag displaysthe number 10: <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> <h:outputText value="#{UserNumberBean.maximum}"/>Thevalue attributes of the tags get the values from theminimum andmaximum properties ofUserNumberBean usingvalue expressions, which are used to reference datastored in other objects, such as beans. SeeBacking Beans for more informationon value expressions. With the addition of theoutputText tags (along with some static text), thegreeting page looks like the following: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> <h2>Hi. My name is Duke. I’m thinking of a number from <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> </h:form></f:view>Adding an ImageTo display images on a page, you use thegraphicImage tag. Theurlattribute of the tag specifies the path to the image file. Let’s addDuke to the page using agraphicImage tag: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> <h2>Hi. My name is Duke. I’m thinking of a number from <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> <h:graphicImage url="/wave.med.gif" /> </h:form></f:view>Adding a Text FieldTheinputText tag represents a text field component. In theguessNumber example,this text field takes an integer input value. The instance of this tagincluded ingreeting.jsp has three attributes:id,label, andvalue. <h:inputText label="User Number" value="#{UserNumberBean.userNumber}"> ...</h:inputText>Theid attribute corresponds to the ID of the component object represented bythis tag. In this case, anid attribute is required because themessagetag (which is used to display validation error messages) needs it to referto theuserNo component. Thelabel attribute specifies the name to be used by error messages torefer to the component. In this example, label is set toUser Number. Asan example, if a user were to enter 23, the error message thatwould be displayed is: User Number: Validation Error: Value is greater than allowable maximum of 10. Thevalue attribute binds theuserNo component value to the bean propertyUserNumberBean.userNumber,which holds the data entered into the text field. After adding theinputText tag, the greeting page looks like the following: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> <h2>Hi. My name is Duke. I’m thinking of a number from <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> <h:graphicImage url="/wave.med.gif" /> <h:inputText label="User Number" value="#{UserNumberBean.userNumber}"> ... </h:inputText> </h:form></f:view>SeeBacking Beans for more information on creating beans, binding to bean properties, referencingbean methods, and configuring beans. SeeUsing Text Components for more information on theinputText tag. Registering a Validator on a Text FieldBy nesting thevalidateLongRange tag within a text field’s component’s tag, the pageauthor registers aLongRangeValidator onto the text field. This validator checks whetherthe component’s local data is within a certain range, defined by thevalidateLongRangetag’sminimum andmaximum attributes. In the case of the greeting page, you need to validate thenumber the user enters into the text field. So, you add avalidateLongRangetag inside theinputText tag. Themaximum andminimum attributes of thevalidateLongRangetag get their values from theminimum andmaximum properties ofUserNumberBean using thevalue expressions#{UserNumberBean.minimum} and#{UserNumberBean.maximum}. SeeBacking Beans for details on value expressions. After adding thevalidateLongRange tag, the page looks like this: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> <h2>Hi. My name is Duke. I’m thinking of a number from <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> <h:graphicImage url="/wave.med.gif" /> <h:inputText label="User Number" value="#{UserNumberBean.userNumber}"> <f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" /> </h:inputText> </h:form></f:view>For more information on the standard validators included with JavaServer Faces technology, seeUsing the Standard Validators. Adding a Custom MessageJavaServer Faces technology provides standard error messages that display on the page whenconversion or validation fails. In some cases, you might need to override thestandard message. For example, if a user were to enter a letter intothe text field ongreeting.jsp, he or she would see the following errormessage: User Number: ’m’ must be a number between -2147483648 and 2147483647 Example: 9346 This is wrong because the field really only accepts values from 0through 10. To override this message, you add aconverterMessage attribute on theinputText tag.This attribute references the custom error message: <h:inputText label="User Number" value="#{UserNumberBean.userNumber}"converterMessage="#{ErrMsg.userNoConvert}">...</h:inputText>The expression thatconverterMessage uses references theuserNoConvert key of theErrMsg resource bundle.The application architect needs to define the message in the resource bundle andconfigure the resource bundle. SeeConfiguring Error Messages for more information on this. SeeReferencing Error Messages for more information on referencing error messages. Adding a ButtonThecommandButton tag represents the button used to submit the data entered inthe text field. Theaction attribute specifies an outcome that helps thenavigation mechanism decide which page to open next.Defining Page Navigation discusses this further. With the addition of thecommandButton tag, the greeting page looks like thefollowing: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> <h2>Hi. My name is Duke. I’m thinking of a number from <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> <h:graphicImage url="/wave.med.gif" /> <h:inputText label="User Number" value="#{UserNumberBean.userNumber}"> <f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" /> </h:inputText> <h:commandButton action="success" value="Submit" /> </h:form></f:view>SeeUsing Command Components for Performing Actions and Navigation for more information on thecommandButton tag. Displaying Error MessagesAmessage tag is used to display error messages on a page whendata conversion or validation fails after the user submits the form. Themessagetag ingreeting.jsp displays an error message if the data entered inthe field does not comply with the rules specified by theLongRangeValidator implementation, whosetag is registered on the text field component. The error message displays wherever you place themessage tag on the page.Themessage tag’sstyle attribute allows you to specify the formatting style forthe message text. Itsfor attribute refers to the component whose valuefailed validation, in this case theuserNo component represented by theinputText tagin thegreeting.jsp page. Put themessage tag near the end of the page: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view> <h:form> <h2>Hi. My name is Duke. I’m thinking of a number from <h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> <h:graphicImage url="/wave.med.gif" /> <h:inputText label="User Number" value="#{UserNumberBean.userNumber}" converterMessage="#{ErrMsg.userNoConvert}"> <f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" /> </h:inputText> <h:commandButton action="success" value="Submit" /> <h:message showSummary="true" showDetail="false" for="userNo"/> </h:form></f:view>Now you have completed the greeting page. Assuming you have also done theresponse.jsp page, you can move on to defining the page navigation rules. Defining Page NavigationDefining page navigation involves determining which page to go to after the userclicks a button or a hyperlink. Navigation for the application is defined inthe application configuration resource file using a powerful rule-based system. Here is oneof the navigation rules defined for theguessNumber example: <navigation-rule> <from-view-id>/greeting.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/response.jsp</to-view-id> </navigation-case></navigation-rule><navigation-rule> <from-view-id>/response.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/greeting.jsp</to-view-id> </navigation-case></navigation-rule> This navigation rule states that when the button on the greeting page isclicked the application will navigate toresponse.jsp if the navigation system is givena logical outcome ofsuccess. In the case of the Guess Number example, the logical outcome isdefined by theaction attribute of theUICommand component that submits the form: <h:commandButton action="success" value="Submit" /> To learn more about how navigation works, seeNavigation Model. Configuring Error MessagesIn case the standard error messages don’t meet your needs, you can createnew ones in resource bundles and configure the resource bundles in your applicationconfiguration resource file. TheguessNumber example has one custom converter message, as describedinAdding a Custom Message. This message is stored in the resource bundle,ApplicationMessages.properties: userNoConvert=The value you entered is not a number. The resource bundle is configured in the application configuration file: <application> <resource-bundle> <base-name>guessNumber.ApplicationMessages</base-name> <var>ErrMsg</var> </resource-bundle></application> Thebase-name element indicates the fully-qualified name of the resource bundle. Thevarelement indicates the name by which page authors refer to the resource bundlewith the expression language. Here is theinputText tag again: <h:inputText label="User Number" value="#{UserNumberBean.userNumber}" converterMessage="#{ErrMsg.userNoConvert}"> ...</h:inputText>The expression on theconverterMessage attribute references theuserNoConvert key of theErrMsgresource bundle. SeeRegistering Custom Error Messages for more information on configuring custom error messages. Developing the BeansDeveloping beans is one responsibility of the application developer. A typical JavaServer Facesapplication couples a backing bean with each page in the application. The backingbean defines properties and methods that are associated with the UI components usedon the page. The page author binds a component’s value to a bean property using thecomponent tag’svalue attribute to refer to the property. Recall that theuserNo component on thegreeting.jsp page references theuserNumber property ofUserNumberBean: <h:inputText label="User Number" value="#{UserNumberBean.userNumber}">...</h:inputText>Here is theuserNumber backing bean property that maps to the data fortheuserNo component: Integer userNumber = null;...public void setUserNumber(Integer user_number) { userNumber = user_number; }public Integer getUserNumber() { return userNumber;}public String getResponse() { if(userNumber != null && userNumber.compareTo(randomInt) == 0) { return "Yay! You got it!"; } else { return "Sorry, "+userNumber+" is incorrect."; }}SeeBacking Beans for more information on creating backing beans. Adding Managed Bean DeclarationsAfter developing the backing beans to be used in the application, you needto configure them in the application configuration resource file so that the JavaServerFaces implementation can automatically create new instances of the beans whenever they areneeded. The task of adding managed bean declarations to the application configuration resource fileis the application architect’s responsibility. Here is a managed bean declaration forUserNumberBean: <managed-bean> <managed-bean-name>UserNumberBean</managed-bean-name> <managed-bean-class> guessNumber.UserNumberBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>minimum</property-name> <property-class>long</property-class> <value>0</value> </managed-property> <managed-property> <property-name>maximum</property-name> <property-class>long</property-class> <value>10</value> </managed-property></managed-bean> This declaration configuresUserNumberBean so that itsminimum property is initialized to 0,itsmaximum property is initialized to 10, and it is added tosession scope when it is created. A page author can use the unified EL to access one ofthe bean’s properties, like this: <h:outputText value="#{UserNumberBean.minimum}"/>For more information on configuring beans, seeConfiguring a Bean. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |