|
Download
FAQ History |
|
API
Search Feedback |
A Simple JavaServer Faces Application
This section describes the process of developing a simple JavaServer Faces application. You'll see what features a typical JavaServer Faces application contains, and what part each role has in developing the application.
Steps in the Development Process
Developing a simple JavaServer Faces application requires performing these tasks:
These tasks can be done simultaneously or in any order. However, the people performing the tasks will need to communicate during the development process. For example, the page author needs to know the names of the model objects in order to access them from the page.
This example asks you to guess a number between 0 and 10, inclusive. The second page tells you if you guessed correctly. The example also checks the validity of your input.
To deploy and execute this example, follow the instructions in Running the Examples Using the Pre-Installed XML Files.
Develop the Model Objects
Developing model objects is the responsibility of the application developer. The page author and the application developer might need to work in tandem to make sure that the component tags refer to the proper object properties, that the object properties have the proper types, and take care of other such details.
Here is the
UserNumberBeanclass that holds the data entered in the text field ongreeting.jsp:package guessNumber; import java.util.Random; public class UserNumberBean { Integer userNumber = null; Integer randomInt = null; String response = null; public UserNumberBean () { Random randomGR = new Random(); randomInt = new Integer(randomGR.nextInt(10)); System.out.println("Duke's Number: "+randomInt); } public void setUserNumber(Integer user_number) { userNumber = user_number; System.out.println("Set userNumber " + userNumber); } public Integer getUserNumber() { System.out.println("get userNumber " + userNumber); return userNumber; } public String getResponse() { if(userNumber.compareTo(randomInt) == 0) return "Yay! You got it!"; else return "Sorry, "+userNumber+" is incorrect."; }As you can see, this bean is just like any other JavaBeans component: It has a set of accessor methods and a private data field for each property. This means that you can conceivably reference beans you've already written from your JavaServer Faces pages.
Depending on what kind of component references a particular model object property, the model object property can be any of the basic primitive and reference types. This includes any of the
Numbertypes,String,int,double, andfloat. JavaServer Faces technology will automatically convert the data to the type specified by the model object property. See Using the HTML Tags and Writing a Model Object Class for information on which types are accepted by which component tags.You can also apply a converter to a component to convert the components value to a type not supported by the component. See Performing Data Conversions for more information on applying a converter to a component.
In the
UserNumberBean, theuserNumberproperty has a type ofInteger. The JavaServer Faces implementation can convert theStringrequest parameters containing this value into anIntegerbefore updating the model object property when you use aninput_numbertag. Although this example converts to anIntegertype, in general, you should use the native types rather than the wrapper classes.Adding Managed Bean Declarations
After developing the beans to be used in the application, you need to add declarations for them in the application configuration file. The task of adding managed bean declarations to the application configuration file can be done by any member of the development team. Here is a managed bean declaration for
UserNumberBean:<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-bean>The JavaServer Faces implementation processes this file on application startup time and initializes the
UserNumberBeanand stores it in session scope. The bean is then available for all pages in the application. For those familiar with previous releases, this managed bean facility replaces usage of thejsp:useBeantag. For more information, see the sections Managed Bean Creation and Application Configuration.Creating the Pages
Authoring the pages is the page author's responsibility. This task involves laying out UI components on the pages, mapping the components to model object data, and adding other core tags (such as validator tags) to the component tags.
Here is the new
greeting.jsppage with the validator tags (minus the surrounding HTML):<HTML> <HEAD> <title>Hello</title> </HEAD> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <body bgcolor="white"> <h:graphic_image id="wave_img" url="/wave.med.gif" /> <h2>Hi. My name is Duke. I'm thinking of a number from 0 to 10. Can you guess it?</h2> <f:use_faces> <h:form id="helloForm" formName="helloForm" > <h:graphic_image id="wave_img" url="/wave.med.gif" /> <h:input_number id="userNo" numberStyle="NUMBER" valueRef="UserNumberBean.userNumber"> <f:validate_longrange minimum="0" maximum="10" /> </h:input_number> <h:command_button id="submit" action="success" label="Submit" commandName="submit" /><p> <h:output_errors id="errors1" for="userNo"/> </h:form> </f:use_faces>This page demonstrates a few important features that you will use in most of your JavaServer Faces applications:
- The
formTag
Theformtag represents an input form, which allows the user to input some data and submit it to the server, usually by clicking a button. The tags representing the components that comprise the form are nested in theformtag. These tags areh:input_numberandh:command_button.- The
input_numberTag
Theinput_numbertag represents a text field component, into which the user enters a number. This tag has three attributes:id,valueRef, andnumberStyle. The optionalidattribute corresponds to the ID of the component object represented by this tag. Theidattribute is optional. If you don't include one, the JavaServer Faces implementation will generate one for you. See Creating Model Objects for more information.
ThevalueRefattribute uses a reference expression to refer to the model object property that holds the data entered into the text field. The part of the expression before the "." must match the name defined by themanaged-bean-nameelement corresponding to the propermanaged-beandeclaration from the application configuration file. The part of the expression after the "." must match the name defined by theproperty-nameelement corresponding to the propermanaged-beandeclaration. In this example, noproperty-nameelements are declared because no properties are initialized on application startup for this example.
ThenumberStyleattribute indicates the number style pattern name as defined by thejava.text.NumberFormatclass. Valid values are:currency,integer,number, orpercent.- The
validate_longrangeTag
Theinput_numbertag also contains avalidate_longrangetag, which is one of a set of standard validator tags included with JavaServer Faces technology. This validator checks if the local value of a component is within a certain range. The value must be anything that can be converted to a long. Thevalidate_longrangetag has two attributes, one that specifies a minimum value and the other that specifies a maximum value. Here, the tag is used to ensure that the number entered in the text field is a number from 0 to 10. See Performing Validation for more information on performing validation.- The
command_buttonTag
Thecommand_buttontag represents the button used to submit the data entered in the text field. Theactionattribute specifies an output that helps the navigation mechanism to decide which page to open next. The next section discusses this further.- The
output_errorsTag
Theoutput_errorstag will display an error message if the data entered in the field does not comply with the rules specified by the validator. The error message displays wherever you place theoutput_errorstag on the page. Theforattribute refers to the component whose value failed validation.Using the JavaServer Faces Tag Libraries discusses the tags in more detail and includes a table that lists all of the basic tags included with JavaServer Faces technology.
The next section discusses the navigation instructions used with this example.
Define Page Navigation
Another responsibility that the application developer has is to define page navigation for the application, such as which page to go to after the user clicks a button to submit a form. The JavaServer Faces navigation model, new for this release, is explained in Navigation Model. Navigating Between Pages explains how to define the navigation rules for an entire application.
The application developer defines the navigation for the application in the application configuration file, the same file in which managed beans are declared.
Here are the navigation rules defined for the
guessNumberexample:<navigation-rule> <from-tree-id>/greeting.jsp</from-tree-id> <navigation-case> <from-outcome>success</from-outcome> <to-tree-id>/response.jsp</to-tree-id> </navigation-case> </navigation-rule> <navigation-rule> <from-tree-id>/response.jsp</from-tree-id> <navigation-case> <from-outcome>success</from-outcome> <to-tree-id>/greeting.jsp</to-tree-id> </navigation-case> </navigation-rule>Each
navigation-ruledefines how to get from one page (specified in thefrom-tree-idelement) to the other pages of the application. Thenavigation-ruleelements can contain any number ofnavigation-caseelements, each of which defines the page to open next (defined byto-tree-id) based on a logical outcome (defined byfrom-outcome).The outcome can be defined by the
actionattribute of theUICommandcomponent that submits the form, as it is in theguessNumberexample:The outcome can also come from the return value of the
invokemethod of anActionobject. The invoke method performs some processing to determine the outcome. One example is that theinvokemethod can check if the password the user entered on the page matches the one on file. If it does, theinvokemethod could return "success"; otherwise, it might return "failure". An outcome of "failure" might result in the logon page being reloaded. An outcome of "success" might result in the page displaying the user's credit card activity opening.To learn more about how navigation works and how to define navigation rules, see the sections Navigation Model and Navigating Between Pages.
|
Download
FAQ History |
|
API
Search Feedback |
All of the material in The Java(TM) Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.