Sunteți pe pagina 1din 43

Pragmatic JSF - Exercises

Pragmatic JSF Exercises

Table of Contents
Exercise: Project Setup ................................................................................................ 4
Objectives ..................................................................................................................................................................... 4 Exercise ......................................................................................................................................................................... 4

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


Objectives ..................................................................................................................................................................... 9 Exercise Part 1................................................................................................................................................................ 9 Exercise Part 2................................................................................................................................................................ 9 Exercise Part 3............................................................................................................................................................. 12 Exercise: Static Navigation................................................................................................................................. 13 Objectives ....................................................................................................................................................................... 13 Exercise ........................................................................................................................................................................... 13

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


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

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


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

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


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

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


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

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


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

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


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

Exercise: Composite Components.............................................................................. 32


Objectives .................................................................................................................................................................. 32 Exercises.................................................................................................................................................................... 32 Exercise Part 1............................................................................................................................................................. 32 Exercise Part 2............................................................................................................................................................. 32

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

2/43

Pragmatic JSF Exercises

Objectives .................................................................................................................................................................. 33 Exercises.................................................................................................................................................................... 33 Exercise Part 1............................................................................................................................................................. 33 Exercise Part 2............................................................................................................................................................. 33 Exercise Part 3............................................................................................................................................................. 33

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


Objectives .................................................................................................................................................................. 35 Exercise ...................................................................................................................................................................... 35

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


Objectives .................................................................................................................................................................. 36 Exercise ...................................................................................................................................................................... 36

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


Objectives .................................................................................................................................................................. 37 Exercises.................................................................................................................................................................... 37 Exercise Part 1 (design) .......................................................................................................................................... 37 Exercise Part 2 (implement) ................................................................................................................................. 37 Sample Layouts ........................................................................................................................................................... 38

Exercise: JSF LifeCycle Events .................................................................................... 41


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

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


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

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

3/43

Pragmatic JSF Exercises

Exercise: Project Setup


Objectives
This set of exercises aims to teach trainees how to create JSF Web Applications from scratch 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 New Maven Project window. Use the following project artifact properties: o group id: com.ctom.labs o artifact id: jsf-jee o version: 0.0.1-SNAPSHOT o packaging: war o name: Pragmatic JSF description: Pragmatic JSF in a JEE Container Click Finish Note: 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 <html></html> tags. Add the following elements in the body of hello.xhtml.

4/43

Pragmatic JSF Exercises

<h:body> <h3>Hello JSF World!</h3> <h:outputText value="One plus Two is #{ 1 + 2 * 3}"/> </h:body>

The statement enclosed in brackets "#{...}" is an EL expression used here to test the validity of the deployment Save and close the hello.xhtml file Edit faces-config.xml Add the following declaration
<?xml version="1.0" encoding="UTF-8"?> <!-- This file is not required if you don't need any extra configuration. --> <faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

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:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

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:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

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


Faces Servlet

<display-name>pragmaticJSF</display-name>

declaration and its mapping

5/43

Pragmatic JSF Exercises

<servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping>

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

<context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param>

There are four possible values for javax.faces.PROJECT_STAGE: Development, UnitTest, SystemTest and Production javax.faces.PROJECT_STAGE == Development produces the most informative messages. Add the welcome-file file list, this will contain only one entry.

<welcome-file-list> <welcome-file>view/hello.jsf</welcome-file> </welcome-file-list>

6/43

Pragmatic JSF Exercises

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:
<build> <finalName>pragmaticJSF</finalName> <plugins> <!-- Compiler plugin enforces Java 1.6 compatibility --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Eclipse plugin automatic source and JavaDoc download --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <configuration> <wtpversion>2.0</wtpversion> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> </plugins> </build>

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

3. 4.

Run the application in Glassfish 3.1 Check-in project after a successful run Make sure eclipse's .* files are excluded (add to SVN Ignore) Add target to SVN Ignore as well

7/43

Pragmatic JSF Exercises

Exercise Sceenshot

8/43

Pragmatic JSF Exercises

Exercise: Project Setup Customization


Objectives
Introduces the required customization parameters for deploying on a non-JEE server, 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, they implement 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 dependencies for 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
<description>Pragmatic JSF in a Servlet container</description> <properties> <!-- JSF Dependency Version --> <jsf.version>2.1.0</jsf.version> <!-- Use UTF-8 as the default source encoding --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>

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 either the <dependencies></dependencies> or <build></build> tags

9/43

Pragmatic JSF Exercises

<repositories> <repository> <!-- Several key Java EE APIs and RIs are in this repository --> <id>java-net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2</url> <layout>default</layout> </repository> <!- Jboss is a good back-up repository --> <repository> <id>repository.jboss.org</id> <name>JBoss Repository</name> <url>http://repository.jboss.org/maven2</url> </repository> </repositories>

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
<dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>${jsf.version}</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>${jsf.version}</version> </dependency>

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

10/43

Pragmatic JSF Exercises

Add the following dependencies for the EL API and Implementation.


<dependency> <groupId>javax.el</groupId> <artifactId>el-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> <scope>provided</scope> </dependency>

Add the following dependencies for the JSTL tag library.


<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>compile</scope> </dependency>

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. <web-app ...version="2.5"/> 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.

11/43

Pragmatic JSF Exercises

<dependency> <groupId>javax.el</groupId> <artifactId>el-api</artifactId> <version>2.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> <scope>runtime</scope> </dependency>

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

<% // dummy file to enable Tomcat 6's support for JSF welcome files %>

You should see the expected "Hello JSF World! 1 + 2" welcome screen.

12/43

Pragmatic JSF Exercises

Exercise: Static Navigation


Objectives
This exercise introduces the students to the very basic elements of a JSF web application 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 nonJSF 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 previous exercise (Tomcat 7) into the current files. o Update your project configuration. Create three new JSF (xhtml) pages: userInfo.xhtml, userDetails.xhtml and summary.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 <-- navigates to the userDetails.xhtml page userDetails.xhtml: Next <-- navigates to summary.xhtml and Previous <-navigatest to userInfo.xhtml summary.xhtml: Previous <-- Navigates to userDetails.xhml Modify web.xml so that the first page that will be loaded after startup is userInfo.xhtml Test by running the application in Tomcat Check-In code to repository after a successful test. Note: Use <table>...</table> tags.

13/43

Pragmatic JSF Exercises

Exercise Reference Screenshot

14/43

Pragmatic JSF Exercises

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 <table>...</table> tags with <h:panelGrid>...</h:panelGrid>

Exercise Snapshot

15/43

Pragmatic JSF Exercises

Exercise: Validation and Conversion


Objectives
This exercise exposes the students to usage of custom and built-in JSF validators and converters. 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 for NumberFormatExceptions. Create a Unit Test for NumberConverter assertEquals(new Integer(21), converter.getAsInteger("X21"));

16/43

Pragmatic JSF Exercises

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

17/43

Pragmatic JSF Exercises

Exercise: Value Change and Action Events


Objectives
This exercise introduces event handling to the students. In order to support value change 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 <Tomcat Home>/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, USA o CA, Canada o GB, United Kingdom o PH, Philippines Edit UserInfoBean Add the following attributes o countryCode, String o zipCode, String o showZipCode, boolean Add the appropriate getters and setters Edit userInfo.xhtml add a h:selectOneMenu for the country and a corresponding label and id o trigger submit() if the country selection is changed o default value is Philippines o 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 the change listener was triggered

18/43

Pragmatic JSF Exercises

add an input text for ZipCode o 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 be rendered 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

19/43

Pragmatic JSF Exercises

Exercise: IoC with Request, View and Custom Scopes


Objectives
A good development practice is to keep the objects that you need in memory for only as 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?

20/43

Pragmatic JSF Exercises

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 be retained 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 the previous exercise and edit as needed. Create a UserPageController for retrieving user information and controlling page flow from the User Info screen.

21/43

Pragmatic JSF Exercises

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<String, String> passwords; o Map<String, String> firstNames; o Map<String, String> lastNames; o Map<String, String> languagePreferences; o Map<String, String> birthdays; o Map<String, String> userCountries; o Map<String, String> userZipCodes; o Key for the UserDatabase maps is the user's login name o UserDatabase has the responsibility of determining if the login/password combination is valid or not. UserOptions for holding the supported language codes, has the following property: Map<String, String> 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 until the user logs out. These are the only properties that should be persisted throughout the user's session You may use Apache commons-lang's set of utilities.

Screens Use the following wireframe diagrams for the individual pages: Login Page

22/43

Pragmatic JSF Exercises

Main Page

23/43

Pragmatic JSF Exercises

User Info Page

Product Selection Page

24/43

Pragmatic JSF Exercises

Verification Page

Check-Out Page

25/43

Pragmatic JSF Exercises

Exercise: Dynamic Navigation


Objectives
This exercise will provide hands-on experience on the usage of advanced navigational 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 exercise as illustrated in the following diagram.

From the confirmation page, if the total amount is zero, navigate back to the product selection page. Otherwise, navigate to the check-out page. Use a Conditional Navigation case (i.e. <if>...</if>) for this part of the exercise. Change the navigation rules such that the Cancel button from the Check-Out page will 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 current page to the help page. Help Page should have a back button that will allow users to navigate back to the page where the help page was invoked from

26/43

Pragmatic JSF Exercises

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 the Main 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.

27/43

Pragmatic JSF Exercises

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.labs o artifact id: form-elements o 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 given some assumptions. The last page (product summary) displays the product definition together with 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

28/43

Pragmatic JSF Exercises

Category: selectMany Options: radio button <think of an additional option to use> Product Options: multi-input type data table o Selected Column: checkbox o Description: read-only text o Opt-In: radio button o Options: selectOne o 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 <Devise some magical computation here> 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 page

Exercise Screenshots
Product Definition Page

29/43

Pragmatic JSF Exercises

Projections Page

Product Summary

30/43

Pragmatic JSF Exercises

31/43

Pragmatic JSF Exercises

Exercise: Composite Components


Objectives
This exercise aims to familiarize the students with the creation and usage of JSF 2.0 composite components. Common use cases that leads to the creation of composite components will also be highlighted in this exercise.

Exercises
Exercise Part 1
Using the Facelets exercise as a starting point create composite components that implements 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 composite component. 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 the introduction of composite components

32/43

Pragmatic JSF Exercises

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 should accept numeric values only. Map out/List all labels, messages and drop down values that are currently in use in the application. Group all values according to its type Assign prefixes as follows: o Labels: label o Messages: msg o Lookup Values: val Create Resource Bundles for the following languages: English Tagalog Japanese German Notes: use Google Translate to translate from one language to another. Use ISO 639 Language Codes Use ISO 3166 Country Codes Replace all hard-coded labels with values from the Resource Bundle Configure the application from Composite Components such that the default language is Tagalog Run the application and validate that all labels are displayed using the correct language.

Exercise Part 2
Modify the validators and converters such that the returned message uses the values 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

33/43

Pragmatic JSF Exercises

Modify the login procedure such that the user's default language is used after the user has logged in. Create a value change listener in for the language drop-down list that changes the 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

34/43

Pragmatic JSF Exercises

Exercise: AJAX with JSF 2.0


Objectives
This exercise aims to introduce AJAX functionalities and its common usage patterns within JSF 2.0

Exercise

Use the application in the Enhanced 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 nonalphanumeric characters in the Product Name field. Check the logs for the Validator log entries. Modify the Ajax event to blur from keyup Run the application and test the new validation mechanism by entering nonalphanumeric 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 AA o Category AB o Category AC Product Type B Categories: o Category BA o Category BB o Category BC o 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 values section should display "-NA-" Run the application and test the new Ajax events

35/43

Pragmatic JSF Exercises

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 login name, password and login button. Use Ajax to disable/enable the login button, if the password length is less than 5 characters the login button should be disabled Ajaxify the language preferences drop down button so that changes will automatically re-render the entire page using the selected language In the User Info page, replace the country drop down list with an auto complete text 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

36/43

Pragmatic JSF Exercises

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 would have 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 different page fragments. Allows logged-in users to change language and account settings at any point in 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 type

Exercise 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

37/43

Pragmatic JSF Exercises

Sample Layouts
Facelets Template Layout

Facelets Login Page

38/43

Pragmatic JSF Exercises

Facelets Sample Page

39/43

Pragmatic JSF Exercises

40/43

Pragmatic JSF Exercises

Exercise: JSF LifeCycle Events


Objectives
This exercise aims to enhance the students' understanding of the JSF LifeCycle and to 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 called com.ctom.labs.listeners. Create a new PhaseListener called GenericPhaseListener. implement the necessary methods create a logger.finest entry that will print the current method and phase that is being invoked create an entry in faces-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 in faces-config.xml Rename the phase listener from GenericPhaseListener to AuthPhaseListener Modify the facelets template(s) such that all pages except for the login page would be mapped to AuthPhaseListener AuthPhaseListener should be associated with PhaseId.RESTORE_VIEW AuthPhaseListener should 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 three fields: 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 the Phase 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.

41/43

Pragmatic JSF Exercises

Exercise JSF State Management


Objectives
This exercise aims to provide the students a deeper understanding on how state is saved 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's web.xml file.
<context-param> <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param>

Run the shopping cart application. Navigate up to the Verification page. Use Firebug to look for a hidden field that looks like the following:
<input id="javax.faces.ViewState" type="hidden" name="javax.faces.ViewState" value="....some very long string...." </input>

Turn off cookies from your browser. Repeat the above. Turn on cookies.

Server State Saving Method


Stop the application Change the STATE_SAVING_METHOD from client to server. Run the application and navigate up to the Verification page. Look for the same hidden field. Turn off cookies from your browser. Repeat the above. Turn on cookies.

Partial State Saving


<Use an existing component's state helper.> <Make students create their own state helper.>

42/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, profiling tools (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

43/43

S-ar putea să vă placă și