JSF Exercises v2 2

download JSF Exercises v2 2

of 43

Transcript of JSF Exercises v2 2

  • 7/22/2019 JSF Exercises v2 2

    1/43

    Pragmatic JSF - Exercises

  • 7/22/2019 JSF Exercises v2 2

    2/43

    Pragmatic JSF Exercises

    2/43

    Table of Contents

    Exercise: Project Setup ................................................................................................ 4Objectives ..................................................................................................................................................................... 4Exercise ......................................................................................................................................................................... 4

    Exercise: Project Setup Customization ......................................................................... 9Objectives ..................................................................................................................................................................... 9

    Exercise Part 1 ................................................................................................................................................................ 9Exercise Part 2 ................................................................................................................................................................ 9Exercise Part 3 ............................................................................................................................................................. 12

    Exercise: Static Navigation................................................................................................................................. 13Objectives ....................................................................................................................................................................... 13Exercise ........................................................................................................................................................................... 13

    Exercise: Managed Beans .......................................................................................... 15

    Exercise ........................................................................................................................................................................... 15

    Exercise: Validation and Conversion ........................................................................ 16Objectives .................................................................................................................................................................. 16

    Exercise Part 1 ............................................................................................................................................................. 16Exercise Part 2 ............................................................................................................................................................. 16

    Exercise: Value Change and Action Events ................................................................. 18

    Objectives .................................................................................................................................................................. 18Exercise Part 1 ............................................................................................................................................................. 18Exercise Part 2 ............................................................................................................................................................. 19

    Exercise: IoC with Request, View and Custom Scopes ................................................ 20 Objectives .................................................................................................................................................................. 20

    Exercise Part 1 ............................................................................................................................................................. 20Exercise Part 2 ............................................................................................................................................................. 21Exercise Part 3 ............................................................................................................................................................. 21

    Exercise: Dynamic Navigation.................................................................................... 26Objectives .................................................................................................................................................................. 26Exercise ...................................................................................................................................................................... 26

    Dynamic Navigation ................................................................................................................................................. 26The Flash Object ......................................................................................................................................................... 27

    Exercise: Enhanced Forms ......................................................................................... 28Objectives .................................................................................................................................................................. 28

    Exercise ...................................................................................................................................................................... 28Project Definition ....................................................................................................................................................... 28Use Case .......................................................................................................................................................................... 28Details .............................................................................................................................................................................. 28Exercise Screenshots ................................................................................................................................................. 29

    Exercise: Composite Components .............................................................................. 32Objectives .................................................................................................................................................................. 32Exercises .................................................................................................................................................................... 32

    Exercise Part 1 ............................................................................................................................................................. 32Exercise Part 2 ............................................................................................................................................................. 32

    Exercise: Resource Bundles ....................................................................................... 33

  • 7/22/2019 JSF Exercises v2 2

    3/43

    Pragmatic JSF Exercises

    3/43

    Objectives .................................................................................................................................................................. 33Exercises .................................................................................................................................................................... 33

    Exercise Part 1 ............................................................................................................................................................. 33Exercise Part 2 ............................................................................................................................................................. 33Exercise Part 3 ............................................................................................................................................................. 33

    Exercise: AJAX with JSF 2.0 ........................................................................................ 35Objectives .................................................................................................................................................................. 35Exercise ...................................................................................................................................................................... 35

    Exercise AJAX with Composite Components .............................................................. 36Objectives .................................................................................................................................................................. 36Exercise ...................................................................................................................................................................... 36

    Exercise: Page Organization using Facelets ................................................................ 37Objectives .................................................................................................................................................................. 37Exercises .................................................................................................................................................................... 37

    Exercise Part 1 (design) .......................................................................................................................................... 37

    Exercise Part 2 (implement) ................................................................................................................................. 37Sample Layouts ........................................................................................................................................................... 38

    Exercise: JSF LifeCycle Events .................................................................................... 41Objectives .................................................................................................................................................................. 41Exercises .................................................................................................................................................................... 41

    Exercise - Phase Listeners ...................................................................................................................................... 41Exercise - System Events ......................................................................................................................................... 41

    Exercise JSF State Management ................................................................................ 42Objectives .................................................................................................................................................................. 42Exercise ...................................................................................................................................................................... 42

    Client State Saving Method ................................................................................................................................... 42Server State Saving Method .................................................................................................................................. 42Partial State Saving .................................................................................................................................................. 42

    Exercise: Tuning Parameters ..................................................................................... 43

  • 7/22/2019 JSF Exercises v2 2

    4/43

    Pragmatic JSF Exercises

    4/43

    Exercise: Project Setup

    Objectives

    This set of exercises aims to teach trainees how to create JSF Web Applications fromscratch with minimal dependencies.This includes, familiarization with settings in the following files:

    web.xml faces-config.xml JSF Pages (header declaration in xhtml files)

    Exercise

    Create a new Maven Project in Eclipse Select the "Create a simple project (skip archetype selection)" in the NewMaven Project window. Use the following project artifact properties:

    o group id: com.ctom.labso artifact id: jsf-jeeo version: 0.0.1-SNAPSHOTo packaging: waro name: Pragmatic JSF

    description: Pragmatic JSF in a JEE Container Click FinishNote: this project will be have the artifact id as eclipse's project name.

    Expand the jsf-jee project folders Ensure that eclipse has recognized this project as a web project Right-Click the project name and choose Maven->Update Project

    Configuration, if not.

    Create the following files under Web Resources (src/main/webapp)/WEB-INF web.xml faces-config.xml

    Create a view folder under Web Resources (src/main/webapp) Create a hello.xhtml file under view

    Right-Click the view folder and select New -> Other Select or Search for XHTML Page (under the GlassFish folder) Enter hello as the file name and click Next (do not click Finish) Select New Facelet Composition Page as a template, click Finish Delete all entries between the tags. Add the following elements in the body of hello.xhtml.

  • 7/22/2019 JSF Exercises v2 2

    5/43

    Pragmatic JSF Exercises

    5/43

    Hello JSF World!

    The statement enclosed in brackets "#{...}" is an EL expression used here totest the validity of the deployment

    Save and close the hello.xhtml file Edit faces-config.xml

    Add the following declaration

    Close the tags, make sure you have a well-formatted xml file. In JSF 2.0, configuration parameters in faces-config.xml is optional.

    1. Edit web.xml Add the following declaration:

    Close the tags, make sure you have a well-formed xml file. web-app version 3.0 is supported by JEE 6 servers, JEE 5 servers support

    only version 2.5 and below.

    web.xml declaration for JEE 5 is as follows:

    Add the following child elements inside web.xml:o display-name

    pragmaticJSF

    o Faces Servletdeclaration and its mapping

  • 7/22/2019 JSF Exercises v2 2

    6/43

    Pragmatic JSF Exercises

    6/43

    Faces Servlet

    javax.faces.webapp.FacesServlet

    1

    Faces Servlet

    *.jsf

    This tells the server to map all requests ending with *.jsf to the Faces Servlet The following entry is optional but this is helpful in debugging JSF 2.0

    applications

    javax.faces.PROJECT_STAGE

    Development

    There are four possible values for javax.faces.PROJECT_STAGE: Development,UnitTest, SystemTest and Production

    javax.faces.PROJECT_STAGE == Development produces the most informativemessages.

    Add the welcome-file file list, this will contain only one entry.

    view/hello.jsf

  • 7/22/2019 JSF Exercises v2 2

    7/43

    Pragmatic JSF Exercises

    7/43

    2. Edit the project's pom.xml file and add the following dependencies: group id: javax, artifact id: javaee-api, version: 6.0, type: jar, scope: provided group id: junit, artifact id: junit, version: 4.8.2, type: jar, scope: test add the following entries:

    pragmaticJSF

    org.apache.maven.plugins

    maven-compiler-plugin

    1.6

    1.6

    org.apache.maven.plugins

    maven-eclipse-plugin

    2.0

    true

    true

    Update your project's configuration (Right Click Project -> Maven -> UpdateProject Configuration)

    3. Run the application in Glassfish 3.14. Check-in project after a successful run

    Make sure eclipse's .* files are excluded (add to SVN Ignore) Add targetto SVN Ignore as well

  • 7/22/2019 JSF Exercises v2 2

    8/43

    Pragmatic JSF Exercises

    8/43

    Exercise Sceenshot

  • 7/22/2019 JSF Exercises v2 2

    9/43

    Pragmatic JSF Exercises

    9/43

    Exercise: Project Setup Customization

    Objectives

    Introduces the required customization parameters for deploying on a non-JEEserver, i.e. Tomcat/Jetty

    Exercise Part 1

    Run jsf-jee on either Tomcat 6 or Tomcat 7, check Tomcat's log file The Hello JSF screen will be rendered but take note of the error messages in

    the log file.

    What did the error message say? Tomcat and Jetty belong to a class of servers called Servlet Engines

    Servlet Engines only implement a small portion of the JEE Specification, i.e.the servlet specification

    Glassfish, WebSphere, JBoss, Geronimo and WebLogic are JEE Servers, theyimplement the full JEE specification that they support (JEE 5 or JEE 6)

    JSF is part of the JEE Spec and is separate from the servlet specification Critical Components that are not included in Servlet Engines

    JSF API and Implementation EL API and Implementation

    Exercise Part 2

    This exercise will pull down, and automatically configure, JSF 2.0 dependenciesfor Servlet Engines.

    Edit pom.xml Change the artifact id to jsf-servlet We want to distinguish this from jsf-jee Edit the description and add the properties tag as shown below

    Pragmatic JSF in a Servlet container

    2.1.0

    UTF-8

    jsf.version will be used as a variable in the configuration file description is just a user friendly description of the project, we want it to be

    accurate

    Add the following repositories entry after eitherthe or tags

  • 7/22/2019 JSF Exercises v2 2

    10/43

    Pragmatic JSF Exercises

    10/43

    java-net

    Java.net Repository for Maven

    http://download.java.net/maven/2default

    repository.jboss.org

    JBoss Repository

    http://repository.jboss.org/maven2

    java.net and jboss has the more updated versions of the JSF API's Remove the dependency on javax:javaee-api:6.0/provided

    This only works for JEE Containers Servlet Engines require specific jars to be downloaded and deployed

    Add the following dependencies for the JSF API and Implementation

    com.sun.faces

    jsf-api

    ${jsf.version}

    com.sun.faces

    jsf-impl

    ${jsf.version}

    The JSF version will be taken from the jsv.version properties definition.

  • 7/22/2019 JSF Exercises v2 2

    11/43

    Pragmatic JSF Exercises

    11/43

    Add the following dependencies for the EL API and Implementation.

    javax.el

    el-api

    2.2

    provided

    org.glassfish.web

    el-impl

    2.2

    provided

    Add the following dependencies for the JSTL tag library.

    javax.servlet

    jstl

    1.2

    compile

    Run the application in Tomcat 7 You should see the Hello JSF World page with the "correct" computation of 1

    + 2

    Run the application in Tomcat 6 If your project is correctly configured, Eclipse will not allow you to run your

    application on Tomcat 6

    Tomcat 6 only supports Java Servlet specification 2.5 and below Check the Project's Facets, it should be set to "Dynamic Web Module, version

    3.0"

    Edit web.xml Change the version to 2.5, i.e. Replace references to web-app_3_0.xsd to web-app_2_5.xsd Right-Click project and select Maven -> Update Project Configuration Check the Project's Facets, it should now be set to "Dynamic Web Module,

    version 2.5"

    This project should now be deployable to both Tomcat 6 and Tomcat 7 Run the application in Tomcat 6

    Check the logs. The application is deployable but not runnable.

    Edit pom.xml Modify the scope of the el-api and elp-impl dependencies as shown below.

  • 7/22/2019 JSF Exercises v2 2

    12/43

    Pragmatic JSF Exercises

    12/43

    javax.el

    el-api

    2.2

    compile

    org.glassfish.web

    el-impl

    2.2

    runtime

    The application should now run in Tomcat 6 without any errors. Run the application in Tomcat 7

    You should see the Hello JSF World page with the "correct" computation of 1+ 2

    Note: This simple example works for both Tomcat 6 and Tomcat 7, however,"regular" JSF 2.0 Applications require different configurations between the

    two Tomcat versions.

    Exercise Part 3

    Run the application in Tomcat 6 The application will be deployed but you will get a 404 Error Tomcat 6 requires a physical file to match the declaration in the welcome file. Our welcome file points to view/hello.jsf

    Create a new file under view, name it hello.jsf Enter the dummy content below

  • 7/22/2019 JSF Exercises v2 2

    13/43

    Pragmatic JSF Exercises

    13/43

    Exercise: Static Navigation

    Objectives

    This exercise introduces the students to the very basic elements of a JSF webapplication as well as to a semi-automated way of configuring a new JSF 2.0 web

    application.

    In this exercise the students will be creating their first JSF form, use common JSF

    tags and use static navigation from one page to another.

    Exercise

    Create a new JSF Web Application. Do not skip archetype selection, click Next. In the the archetype selection window, use the keyword JSF to filter out non-

    JSF archetypes. Select the jsf-servlet-minimal archetype and use the following project

    identifiers for the new project:

    o groupId: com.ctom.labs,o artifactId = pragmaticJSF,o version = 0.0.1-SNAPSHOT

    Compare the web.xml and pom.xml configuration with the previous exercise.o These files show an alternate configuration that will work with Servlet

    Engines and Full JEE Servers.

    o Overwrite the contents of web.xml and pom.xml from the previousexercise (Tomcat 7) into the current files.o Update your project configuration.

    Create three new JSF (xhtml) pages: userInfo.xhtml, userDetails.xhtml andsummary.xhtml

    userInfo.xhtml should have a form with the following text input fields and labels: First Name Last Name

    Navigation Buttons: the pages should have the following buttons userInfo.xhtml: Next

  • 7/22/2019 JSF Exercises v2 2

    14/43

    Pragmatic JSF Exercises

    14/43

    Exercise Reference Screenshot

  • 7/22/2019 JSF Exercises v2 2

    15/43

    Pragmatic JSF Exercises

    15/43

    Exercise: Managed Beans

    Objectives

    This exercise builds upon the previous (Static Navigation)exercise.

    In this exercise, the students will learn how to:

    map managed beans with form elements using basic EL. manipulate user input in JSF, i.e. using Java POJOs as opposed embedded Java

    code (JSP) or JavaScript (basic html).

    use panelGrid and panelGroup JSF tags.Exercise

    Create Two Managed Beans ReferenceData - Application Scope UserInfo - Session Scope

    ReferenceData should have a getter method that returns today's date. UserInfo should have fields and getter/setter methods for the following:

    First Name Last Name

    Edit userInfo.xhtml so that the input fields map to UserInfo's attributes Edit userDetails.xhtml so that the user's full name appears in a welcome message

    on the top left portion of the screen.

    Edit all pages so that today's date appears on the top portion of the screens. Replace ... tags with ...

    Exercise Snapshot

    https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_StaticNavigationhttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_StaticNavigation
  • 7/22/2019 JSF Exercises v2 2

    16/43

    Pragmatic JSF Exercises

    16/43

    Exercise: Validation and Conversion

    Objectives

    This exercise exposes the students to usage of custom and built-in JSF validators andconverters.

    This exercise also introduces the students to the basics of message handling.

    Exercise Part 1

    Edit userDetails.xhtml as shown in the reference screen shot. Add two input text fields: Age and Last Employment Date Add a message display placeholder on the top portion of the form. Add validation message placeholders on the right side of each input field.

    Validate the following using built-in JSF Validators: First Name: Cannot be more than 20 characters Last Name: Cannot be more than 30 characters Add appropriate validation message tags for each input field.

    Use the built-in JSF dateTime converter for the last employment date field. Run the Application

    Intentionally input incorrect/invalid values in all the fields. Observe the messages Adjust the form putting in correct id's in the input fields and form Redeploy the application Observe the messages after entering incorrect/invalid values.

    Exercise Part 2

    Re-Organize Classes create package com.ctom.labs.beans create package com.ctom.labs.validators move UserInfo.java and ReferenceData.java to com.ctom.labs.beans append "Bean" to all class names under com.ctom.labs.beans ensure JSF pages will still work

    Add commons-lang as a project dependency. Create a custom converter

    Converter class name: com.ctom.labs.converter.NumberConverter Converter should implement javax.faces.convert.Converter Converter responsibility is to strip off all non-numeric characters in a String Use StringUtils.strip(String, String) and NumberUtils.createInteger(String)

    from commons-lang

    throw a new ConverterException with a custom FacesMessage forNumberFormatExceptions.

    Create a Unit Test for NumberConverter assertEquals(new Integer(21), converter.getAsInteger("X21"));

    https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_ValidationConversion#Exercise-Validation-and-Conversionhttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_ValidationConversion#Exercise-Validation-and-Conversionhttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_ValidationConversion#Exercise-Validation-and-Conversion
  • 7/22/2019 JSF Exercises v2 2

    17/43

    Pragmatic JSF Exercises

    17/43

    assertEquals(new Integer(121), converter.getAsInteger("X121a")); assertNull(converter.getAsInteger("a12X31")); assertNull(converter.getAsInteger(null)); make sure all tests pass

    Tip: use a protected method for the actual conversion Edit faces-config.xml

    Add an entry for the converter id: com.ctom.labs.numberConverter class: com.ctom.labs.converter.NumberConverter

    Edit userInfo.xhtml Associate NumberConverter with Age

    Deploy Application Enter incorrect/invalid values in all the fields

    Observe the messages.

    Exercise Screenshot

  • 7/22/2019 JSF Exercises v2 2

    18/43

    Pragmatic JSF Exercises

    18/43

    Exercise: Value Change and Action Events

    Objectives

    This exercise introduces event handling to the students. In order to support valuechange events, the following JSF elements/objects will be used:

    SelectItem object h:selectOneMenu f:selectItems onchange attribute rendered attribute

    As a side topic, students are shown how to configure loggers (java.util.logging)

    starting with this exercise.

    Exercise Part 1 Configure Logging

    Go to the /conf directory Open logging.properties file Add an entry (last line) - com.ctom.labs.level = FINEST Moving forward, there should be minimal logger.info statements. Use

    logger.fine or logger.finest instead.

    Edit ReferenceDataBean create a public method called getCountryList that returns a List of

    SelectItem's List of SelectItem's is a list of countries with the corresponding country code

    and label

    o US, USAo CA, Canadao GB, United Kingdomo PH, Philippines

    Edit UserInfoBean Add the following attributes

    o countryCode, Stringo

    zipCode, Stringo showZipCode, boolean

    Add the appropriate getters and setters Edit userInfo.xhtml

    add a h:selectOneMenu for the country and a corresponding label and ido trigger submit() if the country selection is changedo default value is Philippineso create and bind a value change listener to switch the showZipCode

    flag depending on the new value

    o add a logger.fine entry in the value change listener to track if thechange listener was triggered

  • 7/22/2019 JSF Exercises v2 2

    19/43

    Pragmatic JSF Exercises

    19/43

    add an input text for ZipCodeo use rendered attribute to control the visibility of the field, label and

    message

    o if the user chooses USA, zip code input field and label should berendered

    Run the application Enter Invalid Values Observe behavior Enter Valid Values Observe behavior

    Exercise Part 2

    Edit userInfo.xhtml create and bind an action listener event to the next button action listener sets the value of zipCode to NA if the countryCode is not US add logger.fine entries for debugging your code

    Edit userDetails.xhtml Add labels and output texts for countryCode and zipCode

    Run the application Change Country selection Navigate back and forth between userInfo and userDetails Verify expected behavior Fix if necessary

    Sample Snapshot

  • 7/22/2019 JSF Exercises v2 2

    20/43

    Pragmatic JSF Exercises

    20/43

    Exercise: IoC with Request, View and Custom Scopes

    Objectives

    A good development practice is to keep the objects that you need in memory for onlyas long as you need them. The correct usage of Scopes helps enforce this practice.

    Additionally, there are certain types of information that can be considered as volatile

    and hence should not be kept within an entire session. This exercise shows how this

    can be implemented using the correct scope. Additionally, this exercises practices

    the usage and implementation of the IoC (Inversion of Control) Pattern using JSF

    2.0's Managed Beans.

    In this exercise, students will get to use other Managed Bean Scopes (aside from the

    previously used Application and Session Scopes):

    @ViewScoped @RequestScoped @CustomScoped

    Both the xml-based (faces-config.xml) and JSF 2.0 Annotation-based configuration

    will be used in managing dependencies and initializations.

    Exercise Part 1

    Create a new package com.ctom.labs.controller Create a new Managed Bean under this controller.

    LoginController, @ViewScoped Name this managed bean "login" This will be used later to authenticate the user

    Set Managed Bean Properties Change the scope of UserInfo to @RequestScoped Add a Date birthDate property to the UserInfo class Add String loginName and String password properties to the

    new LoginController class

    Move age and its getters/setters from UserInfo to LoginController Add UserInfo as a ManagedProperty of LoginController Generate getters and setters Modify LoginController.getAge() so that it sets and returns the age based on

    the user's birthday

    Edit userInfo.xhtml Add an input text above age for the user's birthday, use the built-in DateTime

    converter.

    Mark the age input text as readonly Set the value of age as #{login.age}

    Run the application in Tomcat What does the error message signify?

  • 7/22/2019 JSF Exercises v2 2

    21/43

    Pragmatic JSF Exercises

    21/43

    Exercise Part 2

    In a typical application, there are classes and properties that need to be persisted

    throughout the user's session and there are classes and properties that are not

    needed.

    After authenticating a user, for example, the user's password does not need to beretained in memory. In fact, it should be disposed right after the validation process.

    Change the scopes of both LoginController and UserInfo as follows: LoginController, @RequestScoped UserInfo, @ViewScoped

    Run the application The previous error should have been resolved You will be prompted with the UserInfo page from the previous exercises

    Enter valid values in the fields Make sure you trigger the "onSubmit" JavaScript call by changing countries,

    this is just to test the age calculation

    Click Next Observe the output from the userDetails page

    The user's name and zip code will be blank This is because the data stored in the UserInfo Managed Bean has already

    been disposed by navigating from one page to another

    Source:source:/model/pragmaticJSF/branches/IoCandManagedBeansExercise2

    Exercise Part 3

    In this exercise, we will be simulating a simple shopping site.

    Navigation

    The following diagram illustrates the navigation path for the application.

    Design

    Re-use the LoginController, UserInfo classes and relevant pages from theprevious exercise and edit as needed.

    Create a UserPageController for retrieving user information and controllingpage flow from the User Info screen.

    https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/repository/entry/model/pragmaticJSF/branches/IoCandManagedBeansExercise2https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/repository/entry/model/pragmaticJSF/branches/IoCandManagedBeansExercise2
  • 7/22/2019 JSF Exercises v2 2

    22/43

    Pragmatic JSF Exercises

    22/43

    Create Mock Objects as Managed Beans to hold lookup data: Put all mock objects in a new (com.ctom.labs.mocks) package UserDatabase for holding user information, holds the following properties:

    o Map passwords;o

    Map firstNames;o Map lastNames;

    o Map languagePreferences;o Map birthdays;o Map userCountries;o Map userZipCodes;o Key for the UserDatabase maps is the user's login nameo UserDatabase has the responsibility of determining if the

    login/password combination is valid or not.

    UserOptions for holding the supported language codes, has the followingproperty:

    Map languageCodes; Initialize and assign values to UserDatabase and UserOptions properties

    using faces-config.xml

    Use an action method in LoginController for controlling access to the main page. Use the following for logging out of the application

    /**

    * Invalidates the current session, i.e. logs the user out.

    * @return the login page.

    */

    public String logout() {

    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

    return "login.jsf/?faces-redirect=true";

    }

    Product Selection/Purchase segment of the application. Create your own managed bean classes (beans and/or page controllers). Use a custom scope which starts at product selection and ends after the

    check-out page.

    You must always keep track of the user's language setting and login name untilthe user logs out.

    These are the only properties that should be persisted throughout the user'ssession

    You may use Apache commons-lang's set of utilities.Screens

    Use the following wireframe diagrams for the individual pages:

    Login Page

  • 7/22/2019 JSF Exercises v2 2

    23/43

    Pragmatic JSF Exercises

    23/43

    Main Page

  • 7/22/2019 JSF Exercises v2 2

    24/43

    Pragmatic JSF Exercises

    24/43

    User Info Page

    Product Selection Page

  • 7/22/2019 JSF Exercises v2 2

    25/43

    Pragmatic JSF Exercises

    25/43

    Verification Page

    Check-Out Page

  • 7/22/2019 JSF Exercises v2 2

    26/43

    Pragmatic JSF Exercises

    26/43

    Exercise: Dynamic Navigation

    Objectives

    This exercise will provide hands-on experience on the usage of advancednavigational controls like conditional navigation cases and dynamic target view id's

    together with the Flash object.

    Exercise

    Dynamic Navigation

    Modify the navigation rule for the shopping component of the previous exerciseas illustrated in the following diagram.

    From the confirmation page, if the total amount is zero, navigate back to theproduct selection page. Otherwise, navigate to the check-out page.

    Use a Conditional Navigation case (i.e. ...) for this part of theexercise.

    Change the navigation rules such that the Cancel button from the Check-Out pagewill navigate back to the product selection page while the Cancel button from the

    product selection page navigates back to the Main page.

    Use the from-action navigation element for this part of the exercise. Create a Help Page that is accessible from all the pages in the application

    Create a CommandLink in all the pages that will navigate from the currentpage to the help page.

    Help Page should have a back button that will allow users to navigate back tothe page where the help page was invoked from

  • 7/22/2019 JSF Exercises v2 2

    27/43

    Pragmatic JSF Exercises

    27/43

    Use Wildards and Dynamic Target IDs for this part of the exercise Tip: Avoid hard-coding Target ID's, the current View Id can be saved

    using ActionListeners

    The Flash Object

    From the User Info page: if the user changes any value, display the values in theMain page.

    Put the new values in a Flash object and display it on the Main page. The section that displays the above should not be rendered if the Flash object

    does not have any value.

  • 7/22/2019 JSF Exercises v2 2

    28/43

    Pragmatic JSF Exercises

    28/43

    Exercise: Enhanced Forms

    Objectives

    This exercise focuses on the use of additional JSF 2.0 tags/form elements, focusing

    specifically on data tables, together with advanced EL syntax.

    Exercise

    Project Definition

    Create a new servlet-based JSF 2.0 application Use the following project artifact identifier

    o group id: com.ctom.labso artifact id: form-elementso version: 0.0.1-SNAPSHOT

    Refer to the previous exercises for the correct configuration parameters Create three pages:

    Product Definition, this will be the starting page Projections Product Summary

    We will use a straightforward and static navigation for this exercise Product Definition --> Projections --> Product Summary Provide a facility to go back to the previous page starting with Product

    Options

    Use Case

    This application simulates a product definition process. The first page (product definition) defines a product and the associated

    options for the product.

    The second page (projections) calculates the product's profitability givensome assumptions.

    The last page (product summary) displays the product definition togetherwith the calculated projections.

    Make sure the appropriate Managed Beans scope is used in all the backing beans.Details

    Product Definition Page

    Input Fields Product Name: text, alphanumeric Target Market: selectOne

  • 7/22/2019 JSF Exercises v2 2

    29/43

    Pragmatic JSF Exercises

    29/43

    Category: selectMany Options: radio button Product Options: multi-input type data table

    o Selected Column: checkboxo

    Description: read-only texto Opt-In: radio button

    o Options: selectOneo Comment: input Text

    Projections Page

    Input Fields Target: text: numeric values only Ratio: text, numeric values only Percent: text, numeric values only Multi-Year Options: table, use ui:repeat

    Calculate Action

    Summary Page

    Displays all the input text values from the previous pages. Displays the selected records (only) from the data table from the product

    definition page.

    Displays the calculated values and assumptions from the projections pageExercise Screenshots

    Product Definition Page

  • 7/22/2019 JSF Exercises v2 2

    30/43

    Pragmatic JSF Exercises

    30/43

    Projections Page

    Product Summary

  • 7/22/2019 JSF Exercises v2 2

    31/43

    Pragmatic JSF Exercises

    31/43

  • 7/22/2019 JSF Exercises v2 2

    32/43

    Pragmatic JSF Exercises

    32/43

    Exercise: Composite Components

    Objectives

    This exercise aims to familiarize the students with the creation and usage of JSF 2.0composite components. Common use cases that leads to the creation of composite

    components will also be highlighted in this exercise.

    Exercises

    Exercise Part 1

    Using theFacelets exercise as a starting point create composite components thatimplements the same stylesheet for the following page components.

    Input Text Box Output Label Command Buttons SelectOneMenu drop down list Modify the pages such that all pages will use composite components instead

    of the standard JSF tags

    Use "ctom" as the namespace for the composite components Run the application and ensure the behavior is consistent prior to the

    introduction of composite components

    Exercise Part 2

    Combine an Output Label and and Input Text Box into a single compositecomponent.

    Label and InputTextBox value fields should be optional If the Label does not have any value, it should not be rendered If the InputTextBox field is not assigned with a value, it should not be

    rendered

    Create composite component for a Date field This composite component should have built-in validators Use JQuery UI to "equip" the date input field with a pop-up calendar Use this composite component on the Birthday field

    Run the application and ensure the behavior is consistent prior to theintroduction of composite components

    https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_Faceletshttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_Facelets
  • 7/22/2019 JSF Exercises v2 2

    33/43

    Pragmatic JSF Exercises

    33/43

    Exercise: Resource Bundles

    Objectives

    This exercise introduces localization practices using Resource Bundles and locales.In this exercise, all hard-coded labels and messages that have been used in previous

    exercises will be replaced.

    Exercises

    Exercise Part 1

    Add an input field in the User Info page for "Annual Income", this field shouldaccept numeric values only.

    Map out/List all labels, messages and drop down values that are currently in usein the application.

    Group all values according to its type Assign prefixes as follows:

    o Labels: labelo Messages: msgo Lookup Values: val

    Create Resource Bundles for the following languages: English Tagalog Japanese German

    Notes: useGoogle Translate to translate from one language to another. UseISO 639 Language Codes UseISO 3166 Country Codes

    Replace all hard-coded labels with values from the Resource Bundle Configure the application fromComposite Components such that the default

    language is Tagalog

    Run the application and validate that all labels are displayed using the correctlanguage.

    Exercise Part 2

    Modify the validators and converters such that the returned message uses thevalues from the Resource Bundles.

    Run the application Enter invalid values to check that the correct language is used for the error

    messages

    Exercise Part 3

    Change the default language to English

    http://translate.google.com/http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txthttp://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.htmlhttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_CompositeComponentshttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_CompositeComponentshttp://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.htmlhttp://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txthttp://translate.google.com/
  • 7/22/2019 JSF Exercises v2 2

    34/43

    Pragmatic JSF Exercises

    34/43

    Modify the login procedure such that the user's default language is used after theuser has logged in.

    Create a value change listener in for the language drop-down list that changesthe current locale depending on the user selection

    Labels should change if a user selects a different language Number format in the checkout page should change depending on the user's

    selection, use German to test this.

    o Thousands separator for German is period "."o Decimal separator for German is comma ","o Example: 3.521,75

  • 7/22/2019 JSF Exercises v2 2

    35/43

    Pragmatic JSF Exercises

    35/43

    Exercise: AJAX with JSF 2.0

    Objectives

    This exercise aims to introduce AJAX functionalities and its common usage patternswithin JSF 2.0

    Exercise

    Use the application in theEnhanced Forms Exercise. In the Product Definition Page, Ajaxify the Product Name for the keyup event

    Create a validator for the product name Validator should check for non-alphanumeric characters and throws a

    Validator Exception if it finds any

    Create a logger entry every time the validator method is called. Run the application and test the new validation mechanism by entering non-

    alphanumeric characters in the Product Name field.

    Check the logs for the Validator log entries. Modify the Ajax event toblurfromkeyup Run the application and test the new validation mechanism by entering non-

    alphanumeric characters in the Product Name field.

    Check the logs for the Validator log entries. In the Product Definition Page, enable Ajax in the product type field such that

    changes in the selection will automatically re-populate the values as follows:

    Product Type A Categories:o Category AAo Category ABo Category AC

    Product Type B Categories:o Category BAo Category BBo Category BCo Category BD

    In the Projections Page, enable Ajax in the Target, Ratio and Percent fields: Values should be automatically calculated by simply entering values in the

    field

    If there are not enough values for the calculations, the calculated valuessection should display "-NA-"

    Run the application and test the new Ajax events

    https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_EnhancedFormshttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_EnhancedForms
  • 7/22/2019 JSF Exercises v2 2

    36/43

    Pragmatic JSF Exercises

    36/43

    Exercise AJAX with Composite Components

    Objectives

    This exercise aims to introduce the use of AJAX within Composite Components.Exercise

    Modify the shopping application Create a new composite component for the Login fields

    Input elements contained within the composite component are the loginname, password and login button.

    Use Ajax to disable/enable the login button, if the password length is lessthan 5 characters the login button should be disabled

    Ajaxifythe language preferences drop down button so that changes willautomatically re-render the entire page using the selected language

    In the User Info page, replace the country drop down list with an auto completetext box

    Create a new composite component for the auto complete text box List of countries will automatically be displayed based on the characters that

    the users type

    Use Ajax to retrieve the list of countries Use JQuery UI for the JavaScript portion of this exercise

  • 7/22/2019 JSF Exercises v2 2

    37/43

    Pragmatic JSF Exercises

    37/43

    Exercise: Page Organization using Facelets

    Objectives

    Exercises

    Exercise Part 1 (design)

    On a sheet of paper, design a page template(s) and page fragments that wouldhave the following characteristics Allows for page fragments to be dynamically included in specific sections of

    the page.

    Common page elements are consolidated and not repeated across differentpage fragments.

    Allows logged-in users to change language and account settings at any pointin time. Design should include a side bar for displaying news items or context-sensitive

    information.

    On the login page, this section will not be rendered. On succeeding pages, this page fragment would contain instructions/tips for

    the page.

    Use simple plain text to show the dynamic behavior. Identify the major form elements that will be included in the template

    panels/divs sections for the fragments form

    Identify a directory structure that will house the different elements by typeExercise Part 2 (implement)

    Create the template or templates Refactor the shopping application to use the template

    Convert all pages to page fragments Move common elements to the template(s)

    Test the application

  • 7/22/2019 JSF Exercises v2 2

    38/43

    Pragmatic JSF Exercises

    38/43

    Sample Layouts

    Facelets Template Layout

    Facelets Login Page

  • 7/22/2019 JSF Exercises v2 2

    39/43

    Pragmatic JSF Exercises

    39/43

    Facelets Sample Page

  • 7/22/2019 JSF Exercises v2 2

    40/43

    Pragmatic JSF Exercises

    40/43

  • 7/22/2019 JSF Exercises v2 2

    41/43

    Pragmatic JSF Exercises

    41/43

    Exercise: JSF LifeCycle Events

    Objectives

    This exercise aims to enhance the students' understanding of the JSF LifeCycle andto familiarize them with various mechanisms to handle requirements that are not

    easily addressable using the standard JSF form control mechanism.

    Exercises

    Exercise - Phase Listeners

    Create a new package calledcom.ctom.labs.listeners. Create a newPhaseListenercalledGenericPhaseListener .

    implement the necessary methods create a logger.finest entry that will print the current method and phase that

    is being invoked

    create an entry infaces-config.xml for this phase listener Run the application and go through the form one input field/command button at

    a time

    watch the logs and observe how the methods are being invoked. alternatively, you could run the server on debug mode and put breakpoints in

    each Phase Listener method

    Remove the phase listener entry infaces-config.xml Rename the phase listener fromGenericPhaseListenertoAuthPhaseListener Modify the facelets template(s) such that all pages except for the login pagewould be mapped toAuthPhaseListener

    AuthPhaseListenershould be associated withPhaseId.RESTORE_VIEW AuthPhaseListenershould check if the user is logged in. Users should be redirected to the login page if they are not logged in.

    Exercise - System Events

    In the userInfo.xhtml page, break down the "last employment date" to threefields:

    month: input text, numeric values only, range is 1 to 12 day: input text, numeric values only, range is 1 to 31 year: input text, numeric values only, must contain 4 digits

    Attach a system event to this group of fields to check for the validity of the date Remove the AuthPhaseListener mapping from thePhase Listener Exercise Implement the same functionality using a System Event Listener.

    Users should be redirected to the login page if they are not logged in.

    https://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_JSFLifeCycleEvents#Exercise_-_Phase_Listenershttps://p34-apps.sourcerepo.com/redmine/p34/projects/pragmaticjsf/wiki/Exercise_JSFLifeCycleEvents#Exercise_-_Phase_Listeners
  • 7/22/2019 JSF Exercises v2 2

    42/43

    Pragmatic JSF Exercises

    42/43

    Exercise JSF State Management

    Objectives

    This exercise aims to provide the students a deeper understanding on how state issaved and restored in JSF as well as introduce JSF 2.0's Partial State Saving

    mechanism.

    Exercise

    Note: Make sure students use Firefox with the Firebug addon installed for this exercise.

    Client State Saving Method

    Make sure your browser accepts cookies. Add the following parameter in the application'sweb.xmlfile.

    State saving method: 'client' or 'server'

    (=default). See JSF Specification 2.5.2

    javax.faces.STATE_SAVING_METHOD

    client

    Run the shopping cart application. Navigate up to the Verification page. Use Firebug to look for a hidden field that looks like the following:

  • 7/22/2019 JSF Exercises v2 2

    43/43

    Pragmatic JSF Exercises

    Exercise: Tuning Parameters

    Objectives

    This exercise aims to emphasize the importance of correct design and

    implementation in terms of system performance. In order to showcase this, profilingtools (JVisualVM) will also be introduced in this exercise.

    JVM tuning parameters are important but the most critical part in tuning

    applications is to implement or refactor the application code to use the correct

    implementation patterns.

    JVM parameters:

    JVM heap size and server settings Garbage collection parameters Thread pools

    Process threads HTTP listener threads