JavaServer Faces Tour

Document Sample
JavaServer Faces Tour Powered By Docstoc
					JavaServer Faces 1.0 (JSR-127) Tour

           Neoforma
           Hien Luu
            5/11/04
Agenda
   Introduction JSF
   Tour of JSF components
       UI Components
       UI Component Rendering
       Data Conversion and Validation
       Navigation
       Error Handling
       Internationalization
       Custom Component
   Demo
JavaServer Faces (JSF)

 “A UI framework for Java web
      applications” – JSF Spec.

 “Finally, a component model for
     enterprise Java!” – David Geary
JSF Status
   Specification – v1.0
       Team – 32 people
       May 2001 – March 2004
       Servlet 2.3 or higher
       JSP 1.2 or higher
JSF Goals
   Make it easier to develop and maintain web
    based applications:
       Reusable UI components
       UI component state management across requests
       Mechanism for wiring client-generated events to
        server side application code
       Allow custom UI components to be easily built and
        re-used
       A well-defined request processing lifecycle
JSF Design Goals
   Protocol and markup independent
   Managing UI component state across
    requests
   Support form processing
   Provide data validation
   Provide a strong event model
   Provide type conversion
   Provide error and exception handling
   Handle page-to-page navigation
JSF Design Goals
   Designed to be tooled = WYSIWYG
   Target audiences
       Page Authors
       Application Developers
       Component Writers
       Tool Providers
       JSF Implementers
JSF Facts
   Competing with WebForms
   Works with Servlet and Portlet APIs
   Will be a part of J2EE standards
   Ten books coming
       JSF –   Web Application Infrastructure
                      Automatic markup generation
                                                              JSF
    High              Stateful UI Component Model

                 Server Side UI Events & Data Conversion

                       Form Handling & Validation


                            Layer Separation                        Struts
                   Pluggable Initialization Architecture
Abstraction
                Resource Mgmt, Enhanced Error Handling


                Template Reuse, Management And Layout


                     Extensible Template Mechanism

               Java, Session Mgmt, Lifecycle Mgmt, Security   JSP & Servlet
    Low                 Deployment and Packaging
                   HTTP Request & Response Handling
   JSF Architecture & Technology
         Architecture                Technology

  UI Component Model

  Model Object Integration      A Set Of UI Components

      Rendering Model
                                APIs And Programming
Server Side UI Event Handling           Model

Type Conversion & Validation
                                  A JSF Custom Tags
         Navigation

    Internationalization
JSF MVC Model

             Model

             Model




    View                 Controller

  Renderer           Component   Listener
          JSF Application
                   Servlet Container
Client
Devices            JSF Application


Phone
                                        Application      DB
                                           Logic
 PDA           JSF Framework


 Laptop                                Model Objects
                                                       EJB
                                                       Container
           JSF Request Processing Lifecycle
                                            Response Complete               Response Complete



Request     Restore
                         Apply Request         Process         Process            Process
           Component
                             Value             Events         Validations         Events
              Tree


                              Render Response

                       Response Complete                 Response Complete

Response
            Render       Process          Invoke             Process          Update Model
           Response      Events          Application         Events              Values


                           Conversion Errors


                                                                Validation or
                                                                Conversion Errors
JSF - Request Processing Lifecycle
   Restore component tree
       Retrieve/create a component
       Leverage state management to restore previously saved
        values
   Apply Request Values
       Each component retrieves values from request and saved as
        “Submitted Value”
   Process Validations
       Conversion and validation are performed
       “Submitted Values” are converted into “Local values”
   Update Model
       “Local Values” are used to update the model state
JSF - Request Processing Lifecycle
   Invoke Application
       Action listeners and actions are invoked
   Render Response
       Render the page and send it back to client
       JSF Component
                                  Event
                                 Handling                  Render
       Model

                        binds                   has
                                      has

      Id          has                            has
                                UIComponent                 Validators
 Local Value
Attribute Map
                                                   has
                                     has


                    Child
                                              Converters
                UIComponent
JSF Standard UI Components
   UIInput              UICommand
   UIOutput             UIForm
   UISelectBoolean      UIColumn
   UISelectItem
                         UIData
   UISelectMany
                         UIPanel
   UISelectOne
   UISelectMany
   UIGraphic
JSF HTML Tag Library
   JSF Core Tag Library
       Validator, Event Listeners, and Converters
   JSF Standard Library
       Express UI components in JSP
JSF HTML Tag Library
<f:view>
<h:form id=”logonForm”>
 <h:panelGrid columns=”2”>
  <h:outputLabel for=”username”>
    <h:outputLext value=”Username:”/>
  </h:outputLabel>
  <h:inputText id=”username” value=”#{logonBean.username}”/>
  <h:outputLabel for=”password”>
    <h:outputText value=”Password:”/>
  </h:outputLabel>
  <h:inputSecret id=”password” value=”#{logonBean.password}”/>
  <h:commandButton id=”submitButton” type=”SUBMIT”
   action=”#{logonBean.logon}”/>
  <h:commandButton id=”resetButton” type=”RESET”/>
 </h:panelGrid>
</h:form>
</fview>
JSF HTML Tag Library
<table>
 <tr><td>Food Selection:</td></tr>
 <tr><td>
   <h:selectManyCheckBox value=“#{order.foodSelections}”>
      <f:selectItem itemValue=“z” itemLabel=“Pizza” />
      <f:selectItem itemValue=“fc” itemLabel=“Fried Chicken” />
      <f:selectItem itemValue=“h” itemLabel=“Hamburger” />
   </h:selectManyCheckBox>
    </td>
</table>
JSF Rendering Model
        Two Rendering Models (direct or delegated)

    Direct
                         Decoding

                         Encoding
                           Component
   Delegated

   Renderer



               Pluggable look and feel
JSF Rendering Model
   Render kit consists of a set of renders
   JSF reference implement must provide
    a render kit for all the standard UI
    components to generate HTML 4.01
   Custom render kit can be provided to
    render UI components into a specific
    markup language
JSF – Managed Bean
   Use to separate presentation from
    business logic
   Based on JavaBeans
   Similar to Struts ActionForm concept
   Use the declarative model
   Entry point into the model and event
    handlers
JSF – Value Binding
   Bind component value and attribute
    to model objects
    Literal:
    <h:outputText rendered=”true” value=”$1000.00”/>

    Value Binding:
    <h:outputText rendered=”#{user.manager}”
        value=”#{employee.salary}”/>
JSF – Value Binding
   Value binding expression
       Bean properties
       List
       Array
       Map
       Predefine objects- header, header values,
        request parameters, cookie,
        request/session/application scope
        attributes, initial parameters
JSF – Value Binding Expression
<h:outputText value=“#{user.name}” />

<h:outputText value=“Hello There #{user.name}” />

#{!user.manager} – operator (+, -, *, /, % …)

Faces-config.xml
<managed-bean>
 <managed-bean-name>user</managed-bean-name>
 <managed-bean-class>org.User</managed-bean-class>
 <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Support bean property initialization for primitive data type as well as List
   and Map.

Binding expression can be used at the bean configuration at well
  JSF – Predefined Objects
       Variable                              Meaning
header             A Map of HTTP header, only the first value of for each name
headerValues       A Map of HTTP header, String[] of all values for each name
param              A Map of HTTP request parameters, first value of for each name
paramValues        A Map of HTTP header, String[] of all values for each name
cookie             A Map of cookie name and values
initParam          A Map of initialization parameters
requestScope       A Map of all request scope attributes
sessionScope       A Map of all session scope attributes
applicationScope   A Map of all request scope attributes
facesContext       FacesContext instance of this request
view               The UIViewRoot instance of this request
JSF – Method Binding
   Binding an event handler to a method
    <h:commandMethod action=“#{user.login}” />


   Four component attributes:
       Action
       Action listener
       Value change listener
       Validator
JSF Events
   Event notification and listener based on JavaBean
    1.0.1
   Events are fired by each UI component
   Event handlers are registered with each component
   Three standard events
       Value Change Event – generates by UIInput component
       Action Event – generates by UICommand component
       Phase Event – fire by JSF life cycle
   Custom events can easily be created and integrated
    into JSF
           JSF Request Processing Lifecycle
                                                 Response Complete               Response Complete
             Value Change Events

Request     Restore
                              Apply Request         Process         Process            Process
           Component
                                  Value             Events         Validations         Events
              Tree


                                   Render Response

                            Response Complete                 Response Complete

Response
            Render            Process          Invoke             Process          Update Model
           Response           Events          Application         Events              Values


                                Conversion Errors
  Action Listener Events
                                                              Phase Event
                                                                     Validation or
                       Actions are invoked                           Conversion Errors
JSF Events –          Value Change Event

Value Changed Listener:
<h:inputText id=”maxUsers”
  valueChangeListener=“#{user.checkMaxUser}” />

public void checkMaxUser(ValueChangeEvent evt) {
  evt.getNewValue(); // new value
  evt.getOldValue();   // old value
}
JSF Events – Action Event
Action Listener:
<h:commandButton value="Login“
  actionListener=“#{customer.loginActionListener}”
  action=“#{customer.login}” />

public void loginActionListener(ActionEvent e) {

}

public String login() {
  return “OK”;
  // return “FAI”;
}
JSF Events – Listener vs Action
   Listener Handlers
       Implement UI logic
       Have access to event source
       Do not participate in navigation handling
   Action Handlers
       Implement business logic
       Don’t have access to action source
       Returned outcome affects the navigation handling
JSF – Multiple Event Handlers
<h:selectOneMenu value=“#{customer.country}”
  <f:valueChangeListener type=“com.comp.CntrListener”
  <f:valueChangeListener type=“com.comp.CCListener”
</h:selectionOneMenu>

<h:commandButton action=“#{search.doSearch()}”>
  <f:actionListener type=“com.comp.AAciontListener” />
  <f:actionListener type=“com.comp.BActionListener” />
</h:commandButton>
JSF – Phase Event
   It is fired before and after each life-cycle
    phase
   Handle by registered phase listener(s)
   Useful for debugging or highly specialized
    behavior

<faces-config>
 <lifecycle>
   <phase-listener>com.comp.PhaseListener</phase-listener>
 </lifecycle>
</faces-config>
JSF – Do It Immediately
   Want to by pass validation for value
    change event
   Want to by pass validation for action
    event
   Set the immediate attribute to true
       For input components (change locale)
       For command components (cancel
        operation)
JSF Validators
   For validating user input
   0 or more validators can be registered
    with an UIInput component
   Validators are invoked during the
    Process Validations request processing
    phase
   Standard validators and custom
    validator
JSF – Two Step Approach
   Request
             Apply Request
                 Value



             Submitted Value


     N
               Validation      Model Value


                     Y
                                             N
               Local Value     Conversion
JSF Validators
   DoubleRangeValidator
       Any numeric type, between specified maximum
        and minimum values
   LongRangeValidator
       Any numeric type convertible to long, between
        specified maximum and minimum values
   LengthValidator
       String type, between specified maximum and
        minimum values
JSF Validators
Required Validation Example:
<h:inputText value=“#{user.id}” required=“true” />

Length Validation Example:
<h:inputText value=“#{user.password}” >
  <f:validateLength minimum=“6” />
  <f:validator validatorId=“passWordValidator” />
</h:inputText>
JSF Custom Validator
   Implements javax.faces.validator.Validator interface

public class BadWordValidator extends Validator {
  public void validate(FacesContext context, UIComponent comp)
    throws ValidatorException {
     // if fail: add a message to context
     throw new ValidatorException(FacesMessage):
  }
}

<h:inputText value=“#{entry.word}” >
  <f:validator validatorId=“badWordValidator” />
</h:inputText>
JSF Converters
   Type conversion between server-side objects
    and their representation in markup language
   Standard converter implementations
       DateTime
       Number
   Custom convert – implements Converter
    interface
       Object getAsObject(….)
       String getAsString(….)
JSF Converters
Number converter example:

<h:inputText value=“#{rent.amt}” converter=“Number”>
 <f:attribute name=“numberStyle” value=“currency” />
</h:inputText>

Date convert example:
<h:inputText value=“#{rent.dueDate}”
  converter=“DateFormat”>
 <f:attribute name=“formatPattern” value=“MM/DD” />
</h:inputText>
JSF Custom Converter
    Implement javax.faces.convert.Converter

Public class MyConverter implements Converter {
 public Object getAsObject(FacesContext context,
   Component comp, Object value) {
 }

    public String getAsString(FacesContext context,
      Component comp, Object value) {
    }
}
       JSF Navigation
            JSF provides a default navigational
             handler
            Behavior is configured in configuration
             file (faces-config.xml)

              1 Contains *   Navigation       has
Navigation                     Rule
                                                          From View Id


                                          1 Contains *

                                                         Navigation Case
JSF Navigation - Example
<navigation-rule>
 <description>LOGIN PAGE NAVIGATION HANDLING</description>
 <from-view-id> /login.jsp </from-view-id>

 <navigation-case>
  <description>Handle case where login succeeded.</description>
  <display-name>Successful Login</display-name>
  <from-action>#{userBean.login}</from-action>
  <from-outcome>success</from-outcome>
  <to-view-id>/home.jsp</to-view-id>
 </navigation-case>

 <navigation-case>
  <description>User registration for a new user succeeded.</description>
  <display-name>Successful New User Registration</display-name>
  <from-action>#{userBean.register}</from-action>
  <from-outcome>success</from-outcome>
  <to-view-id>/welcome.jsp</to-view-id>
 </navigation-case>

</navigation-rule>
JSF – Error Handling
   javax.faces.application.FacesMessage
      Information, Warning, Error, Fatal

   Contain summary and detail
   <h:messages> - to display all messages
   <h:message> - to display a single
    message for a particular component
   javax.faces.context.FacesContext.addM
    essage(String clientId, FacesMessage)
JSF - HTML & CSS Integration
   HTML Integration
    Pass-through attributes
    <h:inputText size=“5” onblur=“checkValue();” />
   Stylesheets Integration
       Most HTML tags have one or more attributes
        (style, styleClass) for passing style information
    <h:outputText styleClass=“header”
      value=“#{bundle.welcome}” />
    For data table
    <h:dataTable rowClasses=“odd, even”,
     columnClasses=“columnOne, columnTwo” ..
JSF – I18N & L10N Support
   The right message file is loaded
    based on current locale
     Accept-language in HTTP header
     <f:view locale=“en” />

     faces-config.xml

   Message bundles
    <f:loadBundle basename=“org.messages” var=“bundle” />
    <h:outputText value=“#{bundle.welcome}” />
JSF - Custom Component
  Base or Existing
                                R
    Component                         encode
                                E
                                N
                                D
                 set
                                E      decode
    Custom       get            R
   Component


                                    Custom Tag
            Update attributes         Library




         Configuration (faces-config.xml)
  JSF – Behind The Scene
                                    get
         init     FactoryFinder               FacesContextFactory
                                               ApplicationFactory
                                                LifeCycleFactory




                                                          Restore View
Faces                FacesContext
Servlet service                                        Apply Request Value
                     LifeCycle.execute(context)
                                                        Process Validation

                                                       Update Model Value
                     LifeCycle.render(context)
                                                       Invoke Application
JSF - Configuration
<faces-config>
 <application>
   <!– message bundle and supported locale 
 </application>
 <component><!– custom component </component>
 <render-kit><!– renderers </render-kit>
 <validator> <!– validators  </validator>
 <converter> <!– convert  </converter>
 <managed-bean><!– model (beans) </managed-bean>
 <navigation-rule><!– navigation info. </navigation-rule>
</faces-config>
JSF - APIs
   javax.faces
       FactoryFinder to find sub-component factoryies
        (Application, Faces Context, Life Cycle, Render Kit)
   javax.faces.application
       Classes to link application’s business logic to JSF
   javax.faces.component
       APIs for UI components
   javax.faces.component.html
       Concrete classes for component + renderer
JSF - APIs
   Javax.faces.context
       Classes for managing per-request state
        information.
   Javax.faces.convert
       For defining converters
   Javax.faces.el
       Classes for evaluating and processing reference
        expressions
   Javax.faces.lifecycle
       Classes for life cycle management
JSF - APIs
   Javax.faces.event
       Classes for defining events and listeners
   Javax.faces.render
       Classes for defining rendering model
   Javax.faces.validator
       Classes for defining validators
   Javax.faces.webapp
       Classes for integration JSF into web applications
JSF – Two Key Objects
   FacesContext
       Info. about the current request
       Scope is at request/response cycle
       Created by FacesServlet
       Available in the callback method
   LifeCycle
       Acts as a state machine and paces the request
        through the phases
       Delegate the response navigation to the
        ViewHandler
JSF – Fits In Big Picture
   JSP/Servlet
   Struts and other UI framework
   EJBs
JSF - Summary
   Powerful framework based on reusable
    UI components for building web-based
    applications in Java
   Make it easy to develop web-based
    application using WYSIWYG tool
   No file upload support, client side
    validation for standard components
   Will find out in the next 12 months
JSF - Demo
Resources
   http://java.sun.com/j2ee/javaserverfaces
   http://forum.java.sun.com/forum.jsp?forum=427
   http://www.jsfcentral.com
   http://www.corejsf.com
   http://www.theserverside.com
   http://www.javaworld.com

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:1
posted:1/30/2013
language:English
pages:60