javaserver faces jeff schmitt october 5, 2006. introduction to jsf presents a standard framework for...

31
JavaServer Faces Jeff Schmitt October 5, 2006

Upload: olivia-wilkerson

Post on 29-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

JavaServer Faces

Jeff Schmitt

October 5, 2006

Introduction to JSF

• Presents a standard framework for building presentation tiers for web applications

• Provides a set of presentation user interfaces (UI) components

• Provides an event model for wiring the interactions between the UI and the application objects

• Unlike servlet API, does not focus on low-level HTTP request handling

• Included in J2EE framework• IDE-friendly, can allow drag-drop UI coding

JSF Advantages

• Custom UI controls to create complex interfaces• Event handling – events are invoked when forms

are submitted. Events can respond to particular buttons, changes in values, user selections, etc.

• Managed beans– In JSP, you can use <jsp:setProperty property="*"> to

automatically save request parameters in a bean. – JSF extends this capability and adds in several

utilities, which greatly simplifies processing of request parameters

• JSF Expression Language for accessing bean properties and collection elements

JSF Advantages

• Form field validation and conversion – insure form values are in correct format– Convert from string to various other types

• XML and property file-based configuration allows changes to application without changing Java code

• Encourages consistent use of MVC throughout the application

JSF Disadvantages

• Steep learning curve -- requires large JSF API as well as JSP a nd servlet APIs

• Less transparent – much is going on that you cannot see

• Relatively new – less documentation and less support from IDE

• Less flexible -- cannot depart from the approach given by framework. Note: this consistency can be an advantage

JSF Sample Application

• Library book management system• User login (borrower or librarian privileges)• Librarian

– Add a book– Check in a book

• Borrower and Librarian– View all available books– Review all books– Check out a book

Faces Servlet

• Configured in web.xml• URL pattern: *.faces (typically)• Servlet Intercepts request, processes request

parameters, creates events that call user code• XML configuration file: faces-config.xml

– I18n– Navigation rules– Bean definitions

• Implements JSF Lifecycle (next slide)

JSF Lifecycle

JSF creates “component tree”– Each element corresponds to a UI value

• Steps in processing request – 1 Restore view– 2 Apply request values– 3 Process validations– 4 Update model values– 5 Invoke application– 6 Render response

1 Restore view

• Matches request to a view definition, usually a JSP file

• Default view definition adds .jsp to the same request– /view/books.faces -> /view/books.jsp

• Build component tree based on the view definition– Used by all subsequent processing steps– An object hierarchy– State maintained across multiple requests

2 Apply request values

• Analyze HTTP parameters

• Map parameters to specific UI components on the page

• If no parameters, skip to step 6 Render request

3 Process validations

• Cycle through all of the input validations for the components

• If any validations fail– render page with original data– Warning messages may be displayed

4 Update model values

• If the validation process succeeds

• Underlying Java beans associated with each UI component are updated

5 Invoke application

• After the model has been updated

• Invoke any business-logic acions requested by the user

• Determine a result code to be used in 6 Render response

6 Render response

• Render a response for the user

• Depending on result code returned in 5 Invoke Application, – view the page that was originally requested– or render a different page

• <?xml version='1.0' encoding='UTF-8'?>• <!DOCTYPE faces-config PUBLIC• "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"• "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">• <faces-config>• <application>• <locale-config>• <default-locale>en</default-locale>• </locale-config>• </application>• <validator>• <validator-id>ISBNValidator</validator-id>• <validator-class> com.oreilly.jent.jsf.library.validator.ISBNValidator

</validator-class>• </validator>• <navigation rule> …• <managed bean> … • </faces-config>

faces-config.xml

Navigation rules

• First major part of faces-config.xml• Second major part is Managed beans• If faces-config.xml gets too big

– Split it into parts– Add an initialization parameter in web.xml

javax.faces.CONFIG_FILES – Good for large projects with multiple

developers where each module has separate settings

Navigation rules

• Each navagation-rule is like a flowchart “if” with one entry and multiple labelled exits– A single <from-view-id> to match the URI

being processed– When control returns from the module named

here, a result string is returned. For example: success, failure, verify, login

– Multiple <navigation-case> entries• <from-outcome> matches a string • <to-view-id> gives next URI to forward to

• <navigation-rule>• <from-view-id>*</from-view-id>• <navigation-case>• <from-outcome>login</from-outcome>• <to-view-id>/login/index.jsp</to-view-id>• </navigation-case>• <navigation-case>• <from-outcome>home</from-outcome>• <to-view-id>/index.jsp</to-view-id>• </navigation-case>• <navigation-case>• <from-outcome>viewbooks</from-outcome>• <to-view-id>/view/listbooks.jsp</to-view-id>• </navigation-case>• </navigation-rule>

Navigation rules

Navigation rules

• <navigation-rule>• <from-view-id>/index.jsp</from-view-id>• <navigation-case>• <from-outcome>addbook</from-outcome>• <to-view-id>/view/addbook.jsp</to-view-id>• </navigation-case>• <navigation-case>• <from-outcome>adminbooks</from-outcome>• <to-view-id>/view/adminbooks.jsp</to-view-id>• </navigation-case>• </navigation-rule>

Navigation rules

• <navigation-rule>• <from-view-id>/login/index.jsp</from-view-id>• <navigation-case>• <from-outcome>success</from-outcome>• <to-view-id>/login/success.jsp</to-view-id>• </navigation-case>• <navigation-case>• <from-outcome>failure</from-outcome>• <to-view-id>/login/index.jsp</to-view-id>• </navigation-case>• </navigation-rule>

Managed Beans

• Second section of faces-config.xml• Glues the UI given by jsp files to the business logic of

your application• Are simply JavaBeans following standard rules

– a zero-argument (empty) constructor -- either by explicitly defining such a constructor or omit all constructors

– no public instance variables (fields)– use accessor methods instead of allowing direct access to fields– accessed through methods called getXxx and setXxx– If class has method getTitle that returns a String, class issaid to

have a String property named title– Boolean properties use isXxx instead of getXxx– For more on beans, see http://java.sun.com/beans/docs/

Managed Beans

• JSF beans also have action methods– Invoked by JSF in response to a user action or event– Contain the code that manipulates the data model

behind your application– In STRUTS these are called the Action classes and

have to be superclasses of Action

• Two kinds of managed beans, although no technical difference between the two– Model beans – focus on data model of application– Backing beans – focus on UI of the application

Managed Beans

• Beans have four possible scopes – not quite the same as JSP/servlet scopes

• Application – entire application shares a single instance

• Session – new instance of bean when new user begins accessing

• Request – new instance for each request• Scopeless – accessed by other beans and

garbage collected like any other java object when no longer referred to by any object

Managed beans<managed-bean> <managed-bean-name>library</managed-bean-name> <managed-bean-class>com.oreilly.jent.jsf.library.model.Library</managed-bean-

class> <managed-bean-scope>application</managed-bean-scope> </managed-bean>

<managed-bean> <managed-bean-name>usersession</managed-bean-name> <managed-bean-class>com.oreilly.jent.jsf.library.session.UserSession</managed-

bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>

<managed-bean> <managed-bean-name>loginform</managed-bean-name> <managed-bean-class>com.oreilly.jent.jsf.library.backing.LoginForm</managed-

bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>

Managed beans<managed-bean> <managed-bean-name>addbookform</managed-bean-name> <managed-bean-class>com.oreilly.jent.jsf.library.backing.AddBookForm</managed-

bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>

<managed-bean> <managed-bean-name>bookdisplayform</managed-bean-name> <managed-beanclass>

com.oreilly.jent.jsf.library.backing.BookDisplayForm</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>library</property-name> <value>#{library}</value> </managed-property> </managed-bean>

JSF Expression language• Similar but not identical to JSP EL• Allow reference to the managed beans

– Retrieving values from beans– Telling JSF components which bean properties to update– In some cases, same expression does both

• General syntax: #{identifiers and modifiers}• Example:

– uses a JSF HTML-writing tag <h:– Same expression both retrieves value from bean and– Tells JSF where to store submitted value from form– Uses two beans<h:inputText value=“#{usersession.currentUser.username}”/>

JSF EL – built-in objects• applicationScope - containing all application-scope managed beans• Cookie• facesContext - the FacesContext instance associated with the

current request• header - a map with HTTP request headers, one value per name• headerValues - a map with HTTP request headers, containing all

values• initParam - a map with HTTP request parameters, containing all

values • param - a map with HTTP request parameters, one value per name• paramValues - a map with HTTP request parameters• requestScope - a map containing all request-scope managed beans• sessionScope - a map containing all session-scope managed beans• view - the UIViewRoot object associated with the current request

The library application

• index.jsp– <f:view– <h:form> -- no action attribute– usersession.currentUser.username– rendered – a button that appears only for

librarian– <h:outputText– <h:commandButton– <h:commandLink

Navigation

• <h:commandButton action=addbook------------------• <navigation-rule>• <navigation-case>• <from-outcome>addbook</from-outcome>• <to-view-id>/view/addbook.jsp</to-view-id>• </navigation-case>• </navigation-rule>

Navigation case wildcard

• Wildcards allow a set of rules that applies to outcomes originating from any view

• <navigation-rule>• <navigation-case>• <from-outcome>*</from-outcome>• <to-view-id>/view/addbook.jsp</to-view-id>• </navigation-case>• </navigation-rule>

Navigation – dynamic actions

• Control navigation based on outcomes

• confirmCredentials() -- a method in the backing bean associated with login

• Returns a string “success” or “failure”

• --------------------

• <h:commandButton action=“#{loginForm.confirmCredentials}”/>