MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

download MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

of 46

Transcript of MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    1/46

    MVC Frameworks II JavaServer Faces

    Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    2/46

    JavaServer Faces

    2Web Programming

    A framework for building user interfaces for webapplications.

    Builds on concepts introduced by the Struts framework.

    Brings together the benefits of an architecture that cleanlyseparates presentation from business logic and a standardcomponent-based user interface set similar in many ways tothat of Swing widgets.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    3/46

    JavaServer Faces

    3Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    4/46

    4Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    5/46

    JSF and Struts

    5Web Programming

    Similarities:

    JSF also has a clean separation between the components for theModel, View, and Controller layers.

    JSF also has a front controller servlet, called FacesServlet, that isresponsible for receiving requests from clients and then performingthe appropriate actions needed as dictated by the framework.

    Both make use of action handlers separate from the front controllerservlet, though Faces handles this a bit differently than Struts.

    Difference:

    View layer

    Struts provides only a set of tag libraries that added on top of standard HTMLfunctionality.

    JSF provides its own set of interface components, along with a set of taglibraries to express these components as tags and a rendering componentthat translates the UI components into HTML.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    6/46

    Controller

    6Web Programming

    The controller layer of JSF is made up of:

    The controller servlet (FacesServlet)

    A set of XML configuration files

    A set of action handlers

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    7/46

    FacesServlet

    7Web Programming

    Responsible for accepting requests from the client andperforming operations needed to produce the response.

    These operations include: Preparing the UI components required for the request.

    Updating the state of the components.

    Calling the required action handlers (if any).

    Rendering the UI components that are part of the response.

    Provided to us by the JSF framework, and only requiresconfiguration in an application's deployment descriptorbefore it is ready for use.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    8/46

    FacesServlet

    8Web Programming

    To configure FacesServlet for our application:

    ...

    FacesServletjavax.faces.webapp.FacesServlet1...

    FacesServlet*.jsf

    ...

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    9/46

    Action Handlers

    9Web Programming

    Two possible ways of creating an action handler:

    By binding a method of a JavaBean to serve as the action handler.

    By creating an instance of a class implementing the ActionListenerinterface.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    10/46

    Application Method

    10Web Programming

    A method that has been bound to a UI component to serveas its action handler.

    Rules required for creating an application method:

    The method must be declared public. The method must take no parameters.

    The return type of the method must be a String.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    11/46

    11Web Programming

    ...public String performLogin() {

    // forward user to failure use case if loginName is emptyif (loginName == null || loginName.length() < 1) {

    return "failure"}

    User user = null;

    // create business object that will handle actual authorization checkUserService service = new UserService();user = service.login(loginName, password);

    // forward user to failure use case if user is not authorizedif (user == null) {

    return "failure";}

    // retrieve an instance of the FacesContext object// that will give us access to other contexts

    FacesContext ctx = FacesContext.getCurrentInstance();

    // place the result into session scope for use by other components

    Map sessionMap = ctx.getExternalContext().getSessionMap();sessionMap.put(ApplicationConstants.USER_OBJECT, user);

    // since user has successfully completed login, forward to successreturn "success";}

    }...

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    12/46

    Application Method

    12Web Programming

    (Example continued)

    The String returned by the method informs the FacesServlet whichview will next be seen by the user. The Strings are logical names,sometimes called outcomes; these outcomes are matched against

    navigation rules defined in the configuration file. Advantage:

    It lessens the number of objects that developers need to maintain.This method can be in any JavaBean recognized by the framework.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    13/46

    Working with Session Scope

    Objects in JSF

    13Web Programming

    The JSF framework has a different method of accessingsession scope.

    JSF provides access to the session context (as well as othercontexts) with the use of a FacesContext object.

    Example:

    FacesContext ctx = FacesContext.getCurrentInstance();

    ...

    Map sessionMap = ctx.getExternalContext().getSessionMap();sessionMap.put(ApplicationConstants.USER_OBJECT, user);

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    14/46

    ActionListener

    14Web Programming

    The other way of implementing an action handler in JSF isto create a class implementing the ActionListener interface.

    This interface defines a single method:

    public void processAction(ActionEvent event)

    ActionEvent object: Provides the implementing class access to thecomponent that caused the event.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    15/46

    15Web Programming

    public class PerformedActionListener implements ActionListener {

    public void processAction(ActionEvent event) {

    // retrieve the component that fired the event

    UICommand component = (UICommand)event.getComponent();

    // retrieve the name of the button or link

    String commandName = (String)component.getValue();

    // create the business object performing functionality

    LoggingService service = new LoggingService();

    // perform logging operation

    service.logUserAction(commandName);

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    16/46

    Application Methods and

    ActionListeners

    16Web Programming

    Most of the time, it is more appropriate to use applicationmethods to serve as action handlers.

    They can be located in the same class which serves as the backingmodel of a form, and thus have easier access to user-provided data.

    Being in the backing model allows the developer to group togetherthe data and the methods that operate on it in one class, making iteasier to maintain.

    They are able to return "outcomes" which inform the FacesServletthe next view to display. ActionListeners cannot, and so can onlybring the user back to the original page after handling the event.

    ActionListeners are the more appropriate choice though, ifyou want to refactor common functionality that you canreuse across multiple action sources.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    17/46

    Application Methods and

    ActionListeners

    17Web Programming

    We will see later that it is possible to have an applicationmethod and one or more ActionListeners to act as handlersfor a particular action.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    18/46

    faces-config.xml

    18Web Programming

    Primary configuration file for the controller layer of the JSFFramework.

    Contain configuration entries for navigation rules, as well asfor JavaBeans that will be recognized by the framework.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    19/46

    19Web Programming

    This bean serves as the backing model for our login formloginPagesample.LoginPageBeanrequest

    The property that will store the user's login nameloginName

    The property that will store the user's passwordpassword

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    20/46

    20Web Programming

    /login.jsfAny failure result should bring the user to an error pagefailure/error.jsp

    Successful login should bring user to welcome pagesuccess/welcome.jsp

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    21/46

    faces-config.xml

    21Web Programming

    (Example continued)

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    22/46

    faces-config.xml

    22Web Programming

    (Example continued)

    Each managed-bean element serves to define a JavaBean that will be managedand recognized by the framework. It has the following child elements:

    : Does not serve any purpose except to improve readability of the configuration file.: Serves as the logical name by which an instance of this bean can be

    accessed / used within the framework.

    : The fully qualified class name of the JavaBean to be managed.

    : The scope in which this bean is to be stored. Can be request, session,application, or none. Having a value of none means that the bean's state will not be stored inbetween requests.

    : Declares values to be used for initializing properties in the JavaBean. It is notnecessary to create entries for each property in the JavaBean, only for those

    that you want to initialize. Has the following child elements:

    : The JavaBean property to be managed.

    : Defines the fully qualified type of the property. (optional)

    : Sets the value of the property to null.

    : Sets the value of the property to the specified value .

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    23/46

    faces-config.xml

    23Web Programming

    (Example continued)

    Used to define logical mappings for the turning points in your application. It canbe used either to define rules specific to a particular page, or to define rules that

    can be used by any page in the application. Has the following child elements:: Defines the page containing the component tree for which this rule will apply. If not

    specified, then the rule will apply for all in the application. (Optional)

    : Defines one outcome for the navigation rule. Has the following child elements:

    : Defines the outcome that is returned from an action which will determine when the navigation casebecomes active.

    : Defines the next page that will become active if this navigation case becomes active.

    others

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    24/46

    Controller

    24Web Programming

    Summary of things to do for the Controller Layer:

    For one time setup:

    Configure the FacesServlet for use in your application.

    For each web page containing JSF UI Components:

    Create a configuration entry for the managed bean that will serve as the page'sbacking model.

    Create navigation rules which define where application could possibly go nextafter the page.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    25/46

    Model

    25Web Programming

    Backing model

    Classes that will store the state of the UI components in each of thepages.

    Not Model classes when viewed strictly under the perspective of the

    MVC architecture.

    However, when thinking only of UI components, it makes sense tocall them part of the Model.

    Care must be taken in the development of these classes such that they do notinfluence the core functionality of your application (the real Model).

    Creating a backing model: As simple as creating a JavaBean with properties corresponding to

    each component in the page.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    26/46

    26Web Programming

    public class LoginPageBean {private String loginName;

    private String password;

    public String getLoginName() {return loginName;

    }

    public void setLoginName(String loginName) {this.loginName = loginName;

    }

    public String getPassword() {return password;

    }

    public void setPassword(String password) {this.password = password;

    }}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    27/46

    27Web Programming

    This bean serves as the backing model for our login formloginPagesample.LoginPageBeanrequestThe property that will store the user's login name

    loginNameThe property that will store the user's password

    password

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    28/46

    View

    28Web Programming

    The View is undoubtedly the layer where JSF most makesits mark.

    JSF not only provides us with custom tags we can use todisplay our interface using JSPs, it also provides us with a

    component set and a standardized API for accessing andmanipulating them.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    29/46

    JSF-JSP Integration

    29Web Programming

    Login Page

    Please login with your login name and password :



  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    30/46

    JSF-JSP Integration

    30Web Programming

    To make use of JSF components in our JSP pages, weneed to include two tag libraries:

    core: Defines core functionality, such as how to manage the JSFcomponents such that they are able to save state, etc.

    html: Defines tags that tells the browser how to render our JSFcomponents into their HTML equivalents.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    31/46

    JSF-JSP Integration

    31Web Programming

    Once we have included these two tag libraries, we make useof the custom tags that they define.

    From the example:

    : Defined in the core library. All tags defining JSF components must be

    enlosed within this tag and provides a place for JSF implementations to be able tosave the state of our UI components.

    : Defined in the html library. Renders a form in HTML..

    : Defines a label component that is associated with another JSFcomponent. The component it is associated with is indicated by the value in the forattribute while the value it displays as its label is the output of the fieldenclosed within it.

    : Renders the text within its value attribute into its HTML equivalent.

    : Renders an HTML input element of type text.

    : Renders an HTML input element of type password.

    : Renders an HTML button which defaults to SUBMIT.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    32/46

    JSF-JSP Integration

    32Web Programming

    Output of the Sample JSP

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    33/46

    33Web Programming

    Login Page

    Please login with your login name and password :

    Login Name:


    Password :


  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    34/46

    JSF-JSP Integration

    34Web Programming

    From the samples:

    The JSF implementation renders our components as defined in thetags.

    The form element is defined to use the POST method of form submission, with

    the action pointing to the same page. The id values of the HTML elements were prefixed with the name of the form.

    This ensures that the name of the form elements are unique within theapplication, which is necessary for Faces operation.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    35/46

    Value Binding

    35Web Programming

    How to link our components to the backing model?

    From the previous example:

    ...


    ... The # notation that serves as the value for the value attribute binds

    the properties in our LoginPageBean to our UI components.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    36/46

    Value Binding

    36Web Programming

    (Example continued)

    The JSF page is able to associate the loginPage identifier to aninstance of a LoginPageBean due to our entry in the faces-config.xml. The relevant entry is presented below:

    This bean serves as the backing model for our login formloginPagejedi.sample.LoginPageBeanrequest...

    Since the LoginPageBean is declared to be a managed bean in the framework,an instance of LoginPageBean will be created and placed in the configuredscope (if one doesn't already exist) when the JSF page is evaluated. On pagesubmission, the values that the user has entered would be automatically beplaced within the bean's properties.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    37/46

    Registering Action Handlers

    to View Components

    37Web Programming

    JSF introduces the concept of event-based programminginto the web environment.

    Some of the UI components that JSF provides will, given theappropriate user action or input, generate events that can beprocessed by action handlers.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    38/46

    Registering Action Handlers

    to View Components

    38Web Programming

    Example:

    To "register" a handler for a commandButton component:

    ...

    ...

    The # notation binds a method named performLogin found in a bean referencedwith the name loginPage to our button. This time, instead of storing the value forthe component, the bound method acts as the action handler for the button click.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    39/46

    Page Navigation

    39Web Programming

    JSF determines the next screen that will be displayed to theuser upon form submission using the return value of themethod that serves as the action handler for the submitbutton.

    The String value is looked up against navigation rules defined withinthe configuration file.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    40/46

    Page Navigation

    40Web Programming

    Example:

    /login.jsfAny failure result should bring the user to an error page

    failure/error.jspSuccessful login should bring user to welcome page

    success/welcome.jsp

    So, if the performLogin method were to return a value or outcome of"failure", the user will be redirected to error.jsp.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    41/46

    Page Navigation

    41Web Programming

    (Example continued)

    As an alternative to using an action handler, it is also possible tostatically provide the navigation rule to be called:

    ...

    ...

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    42/46

    Other JSF Component Tags

    42Web Programming

    Acts in a way similar to that of the tag in the Strutsframework.

    Exposes messages from the application into the output text.

    Displays an HTML element.

    Takes in an array (or collection of objects) and iterates over them,automatically creating the necessary and elements.

    Defines a child tag named . Content placed inside the body of a tag form the template for the

    column definition for each row in the table.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    43/46

    Other JSF Component Tags

    43Web Programming

    ( continued)

    Example:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    44/46

    Other JSF Component Tags

    44

    Web Programming

    ( continued)

    HTML equivalent

    Ewan

    Coba

    DevonShire

    CaliforniaSan Diego

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    45/46

    Other JSF Component Tags

    45

    Web Programming

    ( continued)

    Attributes include (but are not limited to):

    value: Defines the collection or array to be iterated over. This could be either aproperty inside a managed bean or a method in a bean that will return thenecessary content.

    var: Defines the name of the variable which will expose the contents of thecollection or array being iterated over. This variable is visible only within the tag.

    border, cellspacing: Standard HTML table attributes

    rowClasses: A comma-delimited list of CSS styles that will be alternately appliedto each of the rows in the table.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter09 Java Server Faces

    46/46

    Other JSF Component Tags

    46

    Web Programming

    Container tags like only allow JSF tags within theirbody. This means that custom tags or even JSTL tags won't workinside of them. This can be circumvented with the use of the tag.