Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Table of Contents
Exercise: Project Setup ................................................................................................ 4
Objectives ..................................................................................................................................................................... 4 Exercise ......................................................................................................................................................................... 4
2/43
Objectives .................................................................................................................................................................. 33 Exercises.................................................................................................................................................................... 33 Exercise Part 1............................................................................................................................................................. 33 Exercise Part 2............................................................................................................................................................. 33 Exercise Part 3............................................................................................................................................................. 33
3/43
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
<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">
<display-name>pragmaticJSF</display-name>
5/43
<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
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.
6/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:
<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
Exercise Sceenshot
8/43
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
<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
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
<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
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
14/43
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
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
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
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
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
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
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
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
Main Page
23/43
24/43
Verification Page
Check-Out Page
25/43
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
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
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
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
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
Projections Page
Product Summary
30/43
31/43
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
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
33/43
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
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
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
37/43
Sample Layouts
Facelets Template Layout
38/43
39/43
40/43
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.
41/43
Exercise
Note: Make sure students use Firefox with the Firebug addon installed for this exercise.
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.
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.
42/43
43/43