490 likes | 634 Views
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES. Lecture 24. George Koutsogiannakis Spring 2011. Topics. Java Server Faces Continue from previous lecture- Standard Tags. Using a managed bean. Registering Listeners. Creating a component with an event listener example.
E N D
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 24 George Koutsogiannakis Spring 2011
Topics • Java Server Faces • Continue from previous lecture- Standard Tags. • Using a managed bean. • Registering Listeners. • Creating a component with an event listener example.
Standard Tags (continued)Example of the View Tag • Following is an example for the View Tag, that holds a Form Component, which in turn is having two Text Components along with a Submit Button. • <f:view locale = "ja" beforeMethod = "#{MyPhaseListener.beforePhase}" afterMethod = "#{MyPhaseListener.afterPhase}" > <h:form> <p>User name: <h:inputText value = "#{UserBean.userName}" id = "userNameTextField" required = "true"> </h:inputText> </p> <p>Password: <h:input Secret value = "#{UserBean.password}" id = "passwordTextField" required = "true"> </h:inputText> </p> <h:commandButton value = "Submit" action = "submit"/> </h:form> </f:view>
Standard Tags (continued)Example of the View Tag • In the previous slide the locale is set to Japanse ('ja' is the Locale Code name for Japanese) • The Phase Listener interface is used to call before and after through the help of 'beforeMethod' and 'afterMethod' attributes. • afterPhase • Handle a notification that the processing for a particular phase has just been completed. • beforePhase • Handle a notification that the processing for a particular phase of the request processing lifecycle is about to begin.
Standard Tags (continued)Example of the View Tag • By phase we mean a phase in the lifecycle of a request (see previous lecture slides). • Let us review the lifecycle phases again: • Reconstitute Component Tree • A JSP page in a JSF application is represented by a component tree. This phase starts the Lifecycle request processing by constructing this tree. • Each component tree has an identifier that is unique throughout the application. The identifier of a component tree is the path information portion of the request URI. For a request with the URI /faces/index.jsp, for instance, the tree identifier is /index.jsp. The constructed component tree is then saved in the FacesContext object for processing by the following request processing phases.
Standard Tags (continued)Example of the View Tag • Apply Request Values • In this phase, the local value of each component in the component tree is updated from the current request. • A value can come from a request parameter, a header, a cookie, and so on. • During this phase, a component may queue events. These events will be processed during the process event steps in the request processing lifecycle.
Standard Tags (continued)Example of the View Tag • Process Validations • After the local value of each component is updated, in the Process Validations phase, the Lifecycle object will validate those values if necessary. • A component that requires validation must provide implementation of the validation logic. • Alternatively, a JSF programmer can register zero or more validators with the component. • If one or more external validators are found, the local value of each component will be validated using the validation logic in these external validators.
Standard Tags (continued)Example of the View Tag • Update Model Values • This phase can be reached only if the local values of all components in the tree are valid. • In this phase, the Lifecycle object updates the application’s model data. • During this phase, a component may again queue events. • Invoke Application • During this phase, the JSF implementation handles any application level events, such as submitting a form or linking to another page. • Render ResponseIn this phase, the JSF implementation renders the response to the client.
Standard Tags (continued)Example of the SubView Tag • Sub View represents a portion of the Display in the Entire Page. • Sub View may be useful in situations where there is a need for a Main Page which is getting information fetched independently from Different Views.
Standard Tags (continued)Example of the SubView Tag • If we wish to represent a portion of a JSP Page as a Sub View, then it has to be embedded into the Sub View Tag with the help of Import/Include Tags : <c:import>, <jsp:include>), and then the Sub View Tag can be embedded within the View Tag. • This Tag is identified by <f:subview> and following is the syntax definition for this Tag, <f:subview id = "SubViewId"> </f:subview>
Standard Tags (continued)Example of the SubView Tag • Assume that there is a Web Page contains several sections like Footer, Header and Advertisements along with other contents. Then subview will be one possible solution for such a kind of View Representation. Consider the following sample which illustrates this, • <f:view> <f:subview id = "header"> <jsp:include page = "header.jsp"/> <-- Other Elements Here --> </f:subview> <f:subview id = "footer"> <jsp:include page = "footer.jsp"/> <-- Other Elements Here --> </f:subview> <f:subview id = "advertisements"> <jsp:include page = "advertisements.jsp"/> <-- Other Elements Here --> </f:subview> </f:view>
Standard Library Tags-Select tags • Select Tags • These are tags used to select Single or Multiple Entries from Select Components Like List-Box, Check-Box or a Radio-Button. • They usually appear as Child Tags under the Select Component Tags and they are used to represent and select Values. The identified Select tags are given as follows. • Select Item Tag • Select Items Tag
Standard Library Tags-Select tags • Example: • <h:selectItem id = "Id" description = "Some Description" itemValue = "itemValue" itemLabel = "itemLabel" value = "selectValue"> </h:selectItem>
Standard Library Tags-Select tags • Another Example: • <h:selectManyMenu id = "seasonListBox"> <f:selectItemitemValue = "Summer_Season" itemLabel = "Summer Season"> <f:selectItem itemValue = "Winter_Season" itemLabel = "Winter Season"> <f:selectItem itemValue = "Spring_Season" itemLabel = "Spring Season"> <f:selectItem itemValue = "Autumn_Season" itemLabel = "Autumn Season"> </h:selectManyMenu>
Standard Library Tags-Select tags • The previous code populates a List-Box Component with Values like 'Summer Season', 'Winter Season', 'Spring Season' and 'Autumn Season'. • Note that the value corresponding to 'itemLabel' attribute is the one that will be shown to the Clients. • The actual value that is sent to the Server is the corresponding value of the attribute 'itemValue'.
Develop model Objects (Managed Bean) • It is the model (M) part in MVC • A regular JavaBeans with read/write properties • May contain application methods and event handlers • Use to hold data from a UI (page) • Creation and lifetime is managed by JSF runtime • application, session, request • JSF keeps the bean's data in sync with the UI
Managed Bean Declaration(faces-config.xml) <managed-bean> <managed-bean-name>LoginFormBean</managed-bean-name> <managed-bean-class> myapp.LoginFormBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>
Create JSF Pages • Must include JSF tag library • HTML and core tags • All JSF tags must enclosed between a set of view tag • Use JSF form and form component tags • <h:input_text> not <input type=”text”> • <h:command_button> not <input type=”submit”> • May include validators and event listeners on any form components
Sample JSF Page (login.jsp) • <f:view> <f:form formName=”logonForm”> <h:panel_grid columns=”2”> <h:output_text value=”Username:”/> <h:input_text id=”userName” length=”16” valueRef=”LoginFormBean.userName”/> <h:output_text value=”Password:”/> <h:input_secret id=”password” length=”16” valueRef=”LoginFormBean.password”/> <h:command_button type=”submit” label=”Log On” actionRef=”LoginFormBean.logon”/> <h:command_button type=”reset” label=”Reset”/> </h:panel_grid> </f:form> </f:view>
Binding UI to Managed Bean Login.jsp <h:input_text id=”userName” valueRef=”LoginFormBean.userName”/> Faces-config.xml LoginFormBean.java <managed-bean> <managed-bean-name> LoginFormBean </managed-bean-name> <managed-bean-class> myapp.LoginFormBean </managed-bean-class> public class LoginFormBean ... public void setUserName(...) { public String getUserName(...) {
Define Page Navigation Rules(Faces-config.xml) • <navigation-rule> <from-tree-id>/login.jsp</from-tree-id> <navigation-case> <from-outcome>success</from-outcome> <to-tree-id>/menu.jsp</to-tree-id> </navigation-case> </navigation-rule> <navigation-rule> <from-tree-id>/login.jsp</from-tree-id> <navigation-case> <from-outcome>failure</from-outcome> <to-tree-id>/error.jsp</to-tree-id> </navigation-case> </navigation-rule>
Registering Listeners on Components • Listeners can be implemented either as classes • The listener id referenced from either a valueChangeListener tag or an actionListener tag and nest the tag inside the component tag • or as backing beans • The method that implements the listener in the bean is referenced from either the component’s valueChangeListener attribute or its actionListener attribute.
Registering Listeners on Components • The JSF event model is based on the event model defined by the JavaBeans specification. • In this model, an event is represented by an instance of an event class. • An event source object fires an event by calling an event notification method on event listener objects registered to receive the event, passing a reference to the event object as a notification method argument.
Registering Listeners on Components • Classes that want to be informed about events are called event listeners. They declare which events they are interested in by implementing the corresponding listener interfaces. • Hence, an event listener that wants to deal with the ActionEvent fired by a command component declares its intent like this:
Registering Listeners on Components • The following phases of the request lifecycle can queue events in the FacesConext instance associated with the request: • Apply Request Values, • Process Validations, • Update Model Values, • Invoke Application • Therefore, the JSF implementation must handle these events after these phases. • Between two phases, the Lifecycle object checks any event listener that needs to be called. • When writing an event listener, you can choose after which phase the listener should be executed. Alternatively, you can write an event listener that is called after various phases.
Registering Listeners on Components Note that an event listener can change the course of the processing flow by indicating to the Lifecycle object that the processing should jump to the last phase or be terminated immediately after the current event processing.
Registering Listeners on Components • A valueChangeListener tag can be inside a component tag • The valueChangeListener tag supports two attributes: • type: References the fully qualified class name of a ValueChangeListener implementation • binding: References an object ( a backing bean) that implements ValueChangeListener • <h:inputText id="name" size="50" value="#{cashier.name}" required="true"> <f:valueChangeListener type="listeners.NameChanged" /> </h:inputText> Component “name” has the listener class “NameChanged” registered with it. The field name in class cashier is set.
Registering Listeners on Components • You can register (bind) a component to a java bean i.e. <h:output_text valueRef=“myBean.result"></h:output_text> • valueRef attribute references the bean myBean • The UIOutput component :output_text receives its value form the resultproperty of the bean • In the code below an ActionListener is registered with the command_button component: <h:command_button id="submitButton" label="Add" commandName="submit" > <f:action_listener type=“listeners.MyActionListener" /></h:command_button> • You must of course write the java code for the listener class.
Creating a component with an event listener example • Suppose that we have a simple jsp application where a form is generated and sent to the client. • The form has input fields to accept two numbers and print the result of the addition of the two numbers. • There is also a button that, when clicked, fires an ActionEvent and causes an event listener to be executed. • The event listener simply prints the names of the components in the component tree.
Creating a component with an event listener example • The page sent to the client has has five user interface (UI) components: • a UIForm component, • two UIInput components, • a UIOutput component, • and a UICommand component • The UIInput components and the UIOutput component are bound to a JavaBean • The bean stores the two input values and contains the logic of the addition.
Creating a component with an event listener example • The request processing lifecycle always begins with the Reconstitute Component Tree phase. • In this phase, the Lifecycle object builds the component tree representing the requested page. • To be able to draw the tree, you need to create an event listener that will be called during one of the process event steps in the request processing lifecycle.
Creating a component with an event listener example • Our application consists of the following parts: • A JSP page named adder.jsp • An NumberBean JavaBean for storing user data • An action listener called MyActionListener • A deployment descriptor (web.xml) • An application configuration file for registering the JavaBean faces-config.xml • A set of .jar files containing the JSF reference implementation and other libraries should be available ( or if you use NetBeans -they are available)
Creating a component with an event listener example • If we assume that we are going to deploy this application in Tomcat we need a web app directory. The structure of the web app directory is shown on the next slide:
Creating a component with an event listener example • The web.xml file has two important elements in it: • <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>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
Creating a component with an event listener example • The servlet element registers the FacesServlet, and the servlet-mapping element states that any request containing the pattern /faces/ in the URL must be passed to the FacesServlet. • FacesServlet is a servlet that manages the request processing lifecycle for web applications that are utilizing JavaServer Faces to construct the user interface. part of package: javax.faces.webapp.FacesServlet
Creating a component with an event listener example • The code for the java bean needs to be created. • public class NumberBean { int firstNumber = 0; int secondNumber = 0; public NumberBean () { } public void setFirstNumber(int number) { firstNumber = number; } public int getFirstNumber() { return firstNumber; } public void setSecondNumber(int number) { secondNumber = number; } public int getSecondNumber() { return secondNumber;} public int getResult() { return firstNumber + secondNumber;}}
Creating a component with an event listener example • We can make the bean available to the application by registering it in the application configuration file faces-config.xml: • <faces-config> <managed-bean> <managed-bean-name>numberBean</managed-bean-name> <managed-bean-class>ch02a.NumberBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean></faces-config>
Creating a component with an event listener example • The user interface consists of a JSP page called adder.jsp • At the top of the jsp file call the taglibs for the html and core standard tag libraries (see previous letcure) <html><head><title>Add 2 numbers</title></head><body><f:use_faces><h:form formName="addForm" > <br/>First Number: <h:input_number id="firstNumber" valueRef="numberBean.firstNumber"/>
Creating a component with an event listener example <br/>Second Number: <h:input_number id="secondNumber" valueRef="numberBean.secondNumber"/> <br/>Result: <h:output_number id="output" valueRef="NumberBean.result"/> <br/> <h:command_button id="submitButton" label="Add" commandName="submit" > <f:action_listener type="ch02a.MyActionListener" /> </h:command_button></h:form></f:use_faces></body></html>
Creating a component with an event listener example • Note that JSF controls (components) must be enclosed in the opening and closing elements: <f:use_faces>...</f:use_faces> • Inside these elements, you have a form • Inside the form you have: • two input_number controls, • an output_number control, • and a command_button control. • The command button is registered with the ActionListener
Creating a component with an event listener example The component tree of the adder.jsp page
Creating a component with an event listener example-when is event fired? • The last step involves the generation of the code for the ActionListener: MyActionListener. • ActionListener uses the ActionEvent class. • The FacesEvent class—which all JSF events must extend either directly or through one of the standard subclasses, such as ActionEvent—defines a property named phaseId:
Creating a component with an event listener example-when is event fired? • The phaseId property data type is PhaseId, which is a type-safe enumeration containing one value per request processing lifecycle phase: PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS, PhaseId.UPDATE_MODEL_VALUES, PhaseId.INVOKE_APPLICATION, PhaseId.RENDER_RESPONSE, or PhaseId.ANY_PHASE. • The PhaseId.ANY_PHASE value means "process the event in the phase where it was queued," and it's the default value for the phaseId property.
Creating a component with an event listener example-when is event fired? • The UICommand always queues an ActionEvent in the Apply Request Values phase, • it also sets the phaseId to PhaseId.INVOKE_APPLICATION to delay the event handling • unless you tell it that you want to process it immediately. You do so through a UICommand property called immediate. If immediate is true, the phaseId is left unchanged so the event is processed in the Apply Request Values phase.
Creating a component with an event listener example-when is event fired? • Most of the logic for keeping track of the phase in which an event is to be processed is implemented by the UIViewRoot component that sits at the top of the component tree. • At the end of each phase, UIViewRoot goes through the event queue and calls the broadcast() method on all event source components. • It starts with all events with phaseId set to PhaseId.ANY_PHASE and then the events queued for the current phase. • It continues until there are no more events with these phaseId values in the queue, so if processing one event leads to a new event, the new event is also processed, as long as it's for a matching phase.
Creating a component with an event listener example • Our class MyActionListener then will look like: • import javax.faces.event.ActionListener; public class MyActionListener implements ActionListener { ... public void processAction(ActionEvent e) throws AbortProcessingException { Implement the action associated with the event (In our case the drawing of the component tree) ... } }
Creating a component with an event listener example • The ActionListener interface extends the javax.faces.event.FacesListener interface and defines one method, taking an ActionEvent instance as the single argument. • Here is the definition of the ActionListener interface in the library: public interface ActionListener extends FacesListener { public void processAction(ActionEvent event) throws AbortProcessingException; }
Study Guide • EE 5 Tutorial • Chapters 9, 10, 11