52
JavaServer Faces Student Workbook

JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

  • Upload
    others

  • View
    29

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Student Workbook

Page 2: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Page ii Rev 2.1.1 © 2008 ITCourseware, LLC

JavaServer Faces

JavaServer Faces

Author: Jamie Romero

Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112

Contributing Author: Brandon Caldwell, Jim Gallentine

Editor: Jan Waleri

Editorial Staff: Danielle North

Special thanks to: The many instructors whose ideas and careful review have contributed to the quality of

this workbook and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2008 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced or

utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by an

information storage retrieval system, without permission in writing from the publisher. Inquiries should be

addressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.

(303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respective

owners.

Page 3: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

© 2008 ITCourseware, LLC Rev 2.1.1 Page iii

JavaServer Faces

Contents

Chapter 1 - Course Introduction ............................................................................................................. 7

Course Objectives ............................................................................................................................ 8

Course Overview ........................................................................................................................... 10

Using the Workbook ...................................................................................................................... 11

Suggested References ..................................................................................................................... 12

Chapter 2 - Getting Started with JSF .................................................................................................... 15

GUI Development .......................................................................................................................... 16

JavaServer Faces ........................................................................................................................... 18

A JSF Application ........................................................................................................................... 20

JSF Components ............................................................................................................................ 22

Managed Beans .............................................................................................................................. 24

Configuration Files .......................................................................................................................... 26

JSF Application Structure ............................................................................................................... 28

Running the Application ................................................................................................................... 30

Labs ............................................................................................................................................... 32

Chapter 3 - JSF Tag Libraries ............................................................................................................... 35

The JSF Component Tree ............................................................................................................... 36

JSF Tag Libraries ........................................................................................................................... 38

Forms ............................................................................................................................................ 40

Input Tags ...................................................................................................................................... 42

Output Tags .................................................................................................................................... 44

Buttons and Links ........................................................................................................................... 46

Checkboxes ................................................................................................................................... 48

Radio Buttons, Listboxes, and Menus ............................................................................................. 50

Panels ............................................................................................................................................ 52

Labs ............................................................................................................................................... 54

Chapter 4 - Managed Beans ................................................................................................................. 57

Managed Beans and MVC ............................................................................................................. 58

Properties ....................................................................................................................................... 60

Configuring Beans ........................................................................................................................... 62

Bean Scope .................................................................................................................................... 64

Page 4: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Page iv Rev 2.1.1 © 2008 ITCourseware, LLC

JavaServer Faces

Value Bindings ................................................................................................................................ 66

Method Bindings ............................................................................................................................ 68

Dynamic Beans — Lists .................................................................................................................. 70

Dynamic Beans — Maps ................................................................................................................ 72

Advanced Property Initialization ...................................................................................................... 74

Labs ............................................................................................................................................... 76

Chapter 5 - JSF Lifecycle and Event Handling ....................................................................................... 79

JSF Lifecycle Overview .................................................................................................................. 80

Restore View Phase ........................................................................................................................ 82

Apply Request Values Phase ........................................................................................................... 84

Process Validation Phase ................................................................................................................ 86

Update Model Values Phase ........................................................................................................... 88

Invoke Application Phase ................................................................................................................ 90

Render Response Phase ................................................................................................................. 92

JSF Events ..................................................................................................................................... 94

Action Events ................................................................................................................................. 96

Value Change Events ...................................................................................................................... 98

Immediate Events ......................................................................................................................... 100

Labs ............................................................................................................................................. 102

Chapter 6 - Navigation ....................................................................................................................... 105

Navigating Through a JSF Application ........................................................................................... 106

Basic Navigation Configuration ..................................................................................................... 108

From View Id ............................................................................................................................... 110

From Action ................................................................................................................................. 112

Forward vs. Redirect .................................................................................................................... 114

Labs ............................................................................................................................................. 116

Chapter 7 - Data Table Component .................................................................................................... 119

Data and Tables ............................................................................................................................ 120

Basic Structure ............................................................................................................................. 122

Headers and Footers .................................................................................................................... 124

Styles ........................................................................................................................................... 126

Adding Editable Components ........................................................................................................ 128

DataModel ................................................................................................................................... 130

Sorting ......................................................................................................................................... 132

Scrolling ....................................................................................................................................... 134

Labs ............................................................................................................................................. 136

Page 5: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

© 2008 ITCourseware, LLC Rev 2.1.1 Page v

JavaServer Faces

Chapter 8 - Validators and Converters ............................................................................................... 139

Validation and Conversion within the JSF Lifecycle ........................................................................ 140

Converting Dates .......................................................................................................................... 142

Converting Numbers ..................................................................................................................... 144

Displaying Conversion Errors ........................................................................................................ 146

Built-In Validators ......................................................................................................................... 148

Customizing Error Messages ......................................................................................................... 150

Writing Your Own Converter ......................................................................................................... 152

Custom Converter Configuration ................................................................................................... 154

Writing Your Own Validator .......................................................................................................... 156

Labs ............................................................................................................................................. 158

Appendix - Internationalization ............................................................................................................ 161

I18N and L10N ........................................................................................................................... 162

Resource Bundles ......................................................................................................................... 164

Configuring a Resource Bundle ..................................................................................................... 166

Using a Resource Bundle .............................................................................................................. 168

Specifying the Locale .................................................................................................................... 170

I18N in Custom Code .................................................................................................................. 172

Dates and Numbers ...................................................................................................................... 174

Solutions ............................................................................................................................................ 177

Index .................................................................................................................................................. 271

Page 6: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Page vi Rev 2.1.1 © 2008 ITCourseware, LLC

JavaServer Faces

Page 7: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Course Introduction

© 2008 ITCourseware, LLC Rev 2.1.1 Page 7

Chapter 1

Chapter 1 - Course Introduction

Page 8: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Java ServerFaces

Page 8 Rev 2.1.1 © 2008 ITCourseware, LLC

� Describe the JavaServer Faces (JSF) architecture.

� Build a JSF component tree with Core and HTML tag libraries.

� Create JavaBeans with properties and methods that are bound to JSF

components.

� Describe the six phases of the JSF request-processing lifecycle.

� Use both Action Events and Value Change Events to react to user interface

interactions.

� Add entries to faces-config.xml to configure navigation through complex

applications.

� Use the data table component to present tabular information.

� Write your own validators and converters to ensure the legality of user input.

Course Objectives

Page 9: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Course Introduction

© 2008 ITCourseware, LLC Rev 2.1.1 Page 9

Chapter 1

Page 10: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Java ServerFaces

Page 10 Rev 2.1.1 © 2008 ITCourseware, LLC

� Audience: Web developers who want to efficiently create complex web

applications.

� Prerequisites: Completion of Java Web Programming or equivalent

experience.

� Classroom Environment:

� A workstation per student.

Course Overview

Page 11: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Course Introduction

© 2008 ITCourseware, LLC Rev 2.1.1 Page 11

Chapter 1

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When you

lay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topic

page contains the points to be discussed in class. The Support page has code examples, diagrams, screen

shots and additional information. Hands On sections provide opportunities for practical application of key

concepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well as

on-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page provides

the main topics for

classroom discussion.

The Support page has

additional information,

examples and suggestions.

Code examples are in a

fixed font and shaded. The

on-line file name is listed

above the shaded area.

Screen shots show

examples of what you

should see in class.

Topics are organized into

first (�), second (�) and

third (�) level points.

Pages are numbered

sequentially throughout

the book, making lookup

easy.

Callout boxes point out

important parts of the

example code.

Page 12: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Java ServerFaces

Page 12 Rev 2.1.1 © 2008 ITCourseware, LLC

Dudney, Bill, Jonathan Lehr, LeRoy Mattingly, and Bill Willis. 2004. Mastering JavaServer Faces. John

Wiley & Sons, Inc., New York, NY. ISBN 0471462071.

Geary, David and Cay Horstmann. 2007. Core JavaServer Faces, Second Edition. Prentice Hall PTR,

Upper Saddle River, NJ. ISBN 0131738860.

Mann, Kito. 2005. JavaServer Faces in Action. Manning Publications. Greenwich, CT.

ISBN 1932394125.

Schalk, Chris, Ed Burns, and James Holmes. 2006. JavaServer Faces: The Complete Reference.

McGraw-Hill, New York, NY. ISBN 0072262400.

http://java.sun.com/javaee/javaserverfaces/

https://javaserverfaces.dev.java.net/

http://myfaces.apache.org/

http://www.jamesholmes.com/JavaServerFaces/

http://www.jsfcentral.com/

Suggested References

Page 13: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Course Introduction

© 2008 ITCourseware, LLC Rev 2.1.1 Page 13

Chapter 1

Page 14: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Java ServerFaces

Page 14 Rev 2.1.1 © 2008 ITCourseware, LLC

Page 15: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 15

Chapter 2 - Getting Started with JSF

Objectives

� Describe the JavaServer Faces

architecture.

� Identify the most important parts of

a JSF application, including JSF

components and managed beans.

� Write XML deployment descriptors

to configure a JSF application.

� Build and deploy a simple JSF

application.

Page 16: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 16 Rev 2.1.1 © 2008 ITCourseware, LLC

� Client-side Java developers typically use Java's Swing user interface packages to

build Graphical User Interfaces (GUIs).

� Swing provides dozens of components, from simple buttons and text

fields, to complex tables and tree views.

� Swing components generate events that invoke developer's listener code.

� An event occurs when a user interacts with a GUI component.

� An event listener is invoked when its associated event occurs.

� Server-side Java developers typically use JavaServer Pages (JSPs) to generate

HTML that is rendered in the client's browser.

� HTML contains a limited set of user interface components.

� Many developers resort to JavaScript, Java Applets, Flash, or other

technologies for more complex, browser-based user interfaces.

� Any time a change occurs that the backend code needs to react to, a

request must be submitted to the server.

� A Java Servlet typically receives the request and acts as a controller,

determining what to do next.

� Common tasks, such as conversions, validation, and navigation, must be

coded by hand.

GUI Development

Page 17: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 17

The Model-View-Controller (MVC) architecture has been used for years in client-side GUIs. In MVC, the

model represents the data to be presented. The view is made up of the code that handles presentation. The

controller handles decision making, and serves as a conduit between the model and the view. MVC

architectures excel at separating the different concerns involved with GUI development, thus making

applications more maintainable.

Java web developers have adapted MVC for use in web applications. Java Servlets act as controllers,

JavaBeans serve as the model, and JSPs handle the view.

The Jakarta Struts project was created to provide an MVC framework for Java Web Applications. Struts

provides the controller Servlet for you, as well as good built-in support for validation and navigation. Struts

focuses on the control aspect of web applications, rather than the view, or GUI, aspect.

Page 18: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 18 Rev 2.1.1 © 2008 ITCourseware, LLC

� JavaServer Faces (JSF) brings event-driven, component-based GUI

development to the server-side.

� JSF defines GUI components that are independent of a presentation

technology.

� It provides tag libraries that you use to interact with built-in

components or allows you to build your own (or purchase) custom

components.

� JSF specifies an event model so that your server-side GUIs can be coded

like client-side GUIs.

� You can create listeners to handle events that are generated by JSF

components.

� JSF handles basic conversions, validation, and navigation for you, unlike

JSP/Servlet applications, where you need to write this code yourself.

� JavaServer Faces clearly separates the view logic from the business and control

logic.

� JavaBeans provide a layer of abstraction between the user interface and

the business logic.

� The provided FacesServlet handles all control logic on your behalf,

based on entries in faces-config.xml.

� JSPs typically generate the view that is rendered within the client's

browser.

� JavaServer Faces is a specification, not an implementation.

� You will need a JSF implementation in order to use it.

JavaServer Faces

Page 19: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 19

The promise of JSF is that Integrated Development Environments (IDEs) will allow developers to "drag and

drop" JSF components to create user interfaces. Tools such as Sun's Java Studio Creator, Oracle's

JDeveloper, and Eclipse support this type of programming.

Several JSF implementations are available, including:

Sun's JSF Reference Implementation — https://javaserverfaces.dev.java.net/Apache's MyFaces Project — http://myfaces.apache.org/Oracle's ADF Faces — http://www.oracle.com/technology/products/adf/adffaces/index.html

Soft Aspect's WebGalileo Faces — http://javawebcomponents.com/content/products/webGalileoFaces.html

Page 20: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 20 Rev 2.1.1 © 2008 ITCourseware, LLC

� A typical JSF application consists of JSPs, JavaBeans, and XML configuration

files.

� JSPs use special tags to generate the view.

� The JSF-provided tag libraries are used instead of scriptlets within the

JSP.

� You can configure JSF to generate non-HTML views, such as Wireless

Markup Language (WML).

� JavaBeans, known as managed beans, serve as intermediaries to integrate the

back-end business and data access logic with the rest of the application.

� XML deployment descriptors are used to configure the JSF application.

� web.xml declares the provided FacesServlet that handles all control

logic.

� faces-config.xml contains JSF-specific configurations.

A JSF Application

Page 21: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 21

HTML

http://.../xyz.faces

1

6

4

2

3

FacesServlet

Browser

xyz.jsp

managed

bean

business

logic

bean

Web Container

5

Page 22: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 22 Rev 2.1.1 © 2008 ITCourseware, LLC

� The user interface is typically generated by JavaServer Pages.

� JSF tag libraries are used, rather than traditional JSP elements, to generate the

view.

� The Core tag library contains tags that are independent of a presentation

technology.

� The HTML tag library contains tags that are used to generate HTML

output.

� Typical HTML tags include h:form, h:inputText, h:message, and

h:commandButton.

� Other tag libraries can be incorporated to generate non-HTML content.

� Each JSF tag represents an underlying Java object, called a component.

� Components are combined into a renderable component tree.

� When it is time to generate the view, the tree is traversed and each

component renders itself to HTML (or whatever output type you've

configured).

JSF Components

Page 23: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 23

interestCalculator.jsp<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<html>

<f:view>

<head>

<title>Interest Calculator</title>

</head>

<body>

<h2>Interest Calculator</h2>

<h:form id="intCalcForm">

<table>

<tr>

<td>Initial Amount:</td>

<td>

<h:inputText id="amount" value="#{bean.amount}"

size="10" required="true"/>

</td>

<td><h:message for="amount"/></td>

</tr>

<tr>

<td>Interest Rate:</td>

<td>

<h:inputText id="rate" value="#{bean.rate}"

size="4" required="true"/>

</td>

<td><h:message for="rate"/></td>

</tr>

<tr>

<td>Term in Months:</td>

<td>

<h:inputText id="term" value="#{bean.term}"

size="3" required="true"/>

</td>

<td><h:message for="term"/></td>

</tr>

<tr>

<td>

<h:commandButton value="Calculate Interest"

action="#{bean.calculate}"/>

</td>

</tr>

</table>

</h:form>

</body>

</f:view>

</html>

Page 24: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 24 Rev 2.1.1 © 2008 ITCourseware, LLC

� Managed beans are JavaBeans that separate the presentation logic from the

business and data access logic in a JSF application.

� Business and data access logic are typically contained in JavaBeans or

Enterprise JavaBeans.

� Presentation logic is usually embedded in JSPs.

� Managed beans declare properties via gets and sets, that correspond to

components in the view.

� Whenever a view component is rendered, it queries its associated property

for its value.

� The get() method is called.

� Whenever the user submits a request, the view component updates the

property with its value.

� The set() method is called.

� Submitting a request can invoke a method on a managed bean.

� The method usually delegates control to a business logic object.

� The method returns a String that is used for navigation.

Managed Beans

Page 25: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 25

intcalc/jsf/AccountBean.javapackage intcalc.jsf;

import intcalc.model.InterestCalculator;

public class AccountBean {

private double amount;

private int term;

private double rate;

private double total;

private InterestCalculator calc;

public AccountBean() {

calc = new InterestCalculator();

}

public double getAmount() {

return amount;

}

...

public void setAmount(double amt) {

amount = amt;

}

...

public String calculate() {

try {

total = calc.getTotal(amount, rate, term);

return "success";

}

catch (Exception e) {

System.err.println(e);

return "failure";

}

}

}

intcalc/model/InterestCalculator.javapackage intcalc.model;

public class InterestCalculator {

public double getTotal(double amount, double rate, int term) {

return amount * Math.pow(1 + (rate/1200), term);

}

}

The amount property is

defined by the getAmount()

and setAmount() methods.

The calculate() method

delegates control to a

business logic object to

perform the interest

calculation.

The returned

String will be

used for

navigation.

Page 26: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 26 Rev 2.1.1 © 2008 ITCourseware, LLC

� faces-config.xml contains configuration information for the JSF application.

� Each managed bean is declared within a <managed-bean> element.

� The <managed-bean-name> is used within the JSPs to reference the

bean.

� Define the fully-qualified name of the bean class with the <managed-

bean-class> tag.

� You can optionally provide an initial value for each property using the

<managed-property> element.

� Define navigability with the <navigation-rule> element.

� Each <navigation-case> associates the String return value from a

managed bean method with a JSP to forward to.

Configuration Files

Page 27: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 27

faces-config.xml...

<faces-config>

<navigation-rule>

<from-view-id>/interestCalculator.jsp</from-view-id>

<navigation-case>

<from-outcome>success</from-outcome>

<to-view-id>/results.jsp</to-view-id>

</navigation-case>

<navigation-case>

<from-outcome>failure</from-outcome>

<to-view-id>/interestCalculator.jsp</to-view-id>

</navigation-case>

</navigation-rule>

<managed-bean>

<managed-bean-name>bean</managed-bean-name>

<managed-bean-class>intcalc.jsf.AccountBean</managed-bean-class>

<managed-bean-scope>session</managed-bean-scope>

<managed-property>

<property-name>amount</property-name>

<value>10000</value>

</managed-property>

<managed-property>

<property-name>rate</property-name>

<value>2.5</value>

</managed-property>

<managed-property>

<property-name>term</property-name>

<value>60</value>

</managed-property>

</managed-bean>

...

</faces-config>

results.jsp...

<html>

...

<h:outputText value="at #{bean.rate}% interest"/>

<h:outputText value="for #{bean.term} months, yields"/>

...

</html>

If the

AccountBean's

calculate() method

returns success,

then results.jsp will

be invoked.

JSPs will refer to

the AccountBean

by the name bean.

Page 28: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 28 Rev 2.1.1 © 2008 ITCourseware, LLC

� JSF applications are structured like other Java web applications.

� Place all JSP and HTML files at the root level of your application.

� Images and other supporting files are also typically placed at this

location.

� Place web.xml and faces-config.xml in the WEB-INF subdirectory.

� JavaBeans and other supporting Java .class files go under the WEB-INF/

classes directory.

� Make sure that the code's package structure is reflected

appropriately with subdirectories.

� WEB-INF/lib contains .jar files that your application depends on.

� If you deploy a JSF application to a web container that does not

support JSF, you can place the necessary JSF .jar files here.

� Bundle the entire directory structure within a .war file.

� Many developers use the ant build tool from Apache to build and deploy the

.war file.

� Embed instructions to ant within a file named build.xml.

JSF Application Structure

Page 29: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 29

build.xml<project name="InterestCalculator" default="all" basedir=".">

<!-- set global properties for this build -->

<property name="name" value="InterestCalculator"/>

<property name="source" value="."/>

<property name="distDir" value="${source}/dist"/>

<property name="webappDir" value="${source}/webapp"/>

<property name="packageDir" value="${source}/intcalc"/>

<property name="warName" value="${name}.war"/>

<property environment="env"/>

<target name="all" depends="clean, init, compile, genWar, deploy"/>

<target name="init">

<mkdir dir="${webappDir}"/>

<copy todir="${webappDir}">

<fileset dir="${source}">

<include name="*.jsp"/>

<include name="*.html"/>

</fileset>

</copy>

<mkdir dir="${webappDir}/WEB-INF/classes"/>

<copy todir="${webappDir}/WEB-INF"

file="${source}/faces-config.xml" />

<mkdir dir="${webappDir}/META-INF"/>

<copy todir="${webappDir}/META-INF"

file="${source}/context.xml"

failonerror="false"/>

<mkdir dir="${distDir}"/>

</target>

<target name="compile" depends="init">

<javac srcdir="${packageDir}/model"

destdir="${webappDir}/WEB-INF/classes" includes="*.java"/>

<javac srcdir="${packageDir}/jsf"

destdir="${webappDir}/WEB-INF/classes" includes="*.java"/>

</target>

<target name="genWar" depends="compile">

<war warfile="${distDir}/${warName}"

webxml="${source}/web.xml"

basedir="${webappDir}" />

</target>

...

</project>

Try It:Start Tomcat by running %TOMCAT_HOME%\bin\startup.bat. Then build and deploy the JSFapplication by running ant within your current directory.

Page 30: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 30 Rev 2.1.1 © 2008 ITCourseware, LLC

� web.xml declares the provided FacesServlet that handles all control logic.

<servlet>

<servlet-name>FacesServlet</servlet-name>

<servlet-class>

javax.faces.webapp.FacesServlet

</servlet-class>

</servlet>

� The <servlet-mapping> element ensures that all URLs that end in the .faces

suffix are redirected to the FacesServlet.

<servlet-mapping>

<servlet-name>FacesServlet</servlet-name>

<url-pattern>*.faces</url-pattern>

</servlet-mapping>

� You don't access a JavaServer Faces JSP with a .jsp extension, you will

instead use a .faces extension.

� You can optionally define a welcome file to allow a user to access your

application with only the web context.

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

� Place a link in your welcome file to the initial page of your application.

Running the Application

Page 31: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 31

index.html is the welcome

file for this application.

web.xml<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" ...>

<servlet>

<servlet-name>FacesServlet</servlet-name>

<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>FacesServlet</servlet-name>

<url-pattern>*.faces</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

</web-app>

index.html<html>

<head>

<title>Demo</title>

</head>

<body>

<h2>Getting Started with JSF Demo</h2>

<a href="interestCalculator.faces">Interest Calculator</a>

</body>

</html>

Try It:In a web browser go to http://localhost:8080/InterestCalculator/ to access the welcome file for the

JSF application.

Use the .faces extension,

rather than .jsp.

Page 32: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 32 Rev 2.1.1 © 2008 ITCourseware, LLC

Labs

� Create a Java class with methods that perform simple arithmetic, such as addition, subtraction,

multiplication, and division. Pass in the two operands as parameters, return back the result.

(Solution: calculator/model/Calculator.java)

� Create a managed bean with properties for each operand and for the result. Add methods that

delegate the math to the class you wrote in �.

(Solution: calculator/jsf/MathBean.java)

� Create a JSP to serve as the user interface for the application. Your JSP should allow the user to

enter two numbers and click the appropriate button to add, subtract, etc.

(Solution: calculator.jsp)

� Create another JSP that displays the results to the user.

(Solution: results.jsp)

� Build a simple welcome file for the application.

(Solution: index.html)

� Write the deployment descriptors for the application. Make sure that faces-config.xml configures

the managed bean you created in �.

(Solutions: faces-config.xml, web.xml)

� Create an ant build file that builds and deploys the application. Test the application by accessing the

appropriate URL in your browser.

(Solution: build.xml)

Page 33: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 2 Getting Started with JSF

© 2008 ITCourseware, LLC Rev 2.1.1 Page 33

Page 34: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 119

Chapter 7 - Data Table Component

Objectives

� Generate HTML table tags from an array

or List of data.

� Improve the visual appearance of the table

by adding headers, footers, and Cascading

Style Sheets.

� Create editable tables, whose entries are

made up of input components such as text

fields and checkboxes.

� Write a Comparable class to enable

sorting of the table by column.

� Create managed bean methods and

properties to support scrolling behavior

for large tables.

Page 35: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 120 Rev 2.1.1 © 2008 ITCourseware, LLC

� Most Web applications display their data using tables.

� You can use JSTL <c:forEach> syntax to iterate through a list of objects,

displaying them between appropriate HTML table tags.

� You cannot nest JSF tags within the JSTL <c:forEach> tag.

� JSF provides the <h:dataTable> component to simplify the generation of

HTML tables.

� You can wrap the following types of data in an <h:dataTable>:

� Java arrays

� java.util.List

� java.sql.ResultSet

� javax.servlet.jsp.jstl.sql.Result

� javax.faces.model.DataModel

� The underlying data structure is automatically iterated through and each of

its values is wrapped in the appropriate HTML table tags.

Data and Tables

Page 36: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 121

This is JSP EL,

not JSF EL.

The following example uses JSTL:

listPresidents.jsp<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<jsp:useBean id="theBean" class="pres.DataBean"/>

<html>

<f:view>

<head>

<title>US Presidents</title>

</head>

<body>

<h2>US Presidents</h2>

<table>

<c:forEach items="${theBean.allPresidents}" var="pres">

<tr>

<td>${pres.id}</td>

<td>${pres.firstName}</td>

<td>${pres.middleName}</td>

<td>${pres.lastName}</td>

</tr>

</c:forEach>

</table>

</body>

</f:view>

</html>

Try It:Run ant in the chapter directory. Visit http://localhost:8080/DataTable/listPresidents.faces to see the

rendered version of this JSP.

A javax.servlet.jsp.jstl.sql.Result provides a wrapper around a java.sql.ResultSet. The Result object

is typically created using JSTL's SQL tag libraries. You can, however, create a Result object given a

ResultSet by using java.servlet.jsp.jstl.sql.ResultSupport's static toResult() method:

Result result = ResultSupport.toResult(resultSet);

From an architectural standpoint, you should not access a Result or a ResultSet directly from your JSPs.

The view tier should not be so closely tied to the data tier. Instead, use data access objects (DAOs) to

create simple Java classes that act as transfer objects for your JSPs to interact with.

Page 37: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 122 Rev 2.1.1 © 2008 ITCourseware, LLC

� Provide at least two attributes in the <h:dataTable> tag.

<h:dataTable value="#{myBean.racesTimes}" var="time">

� Specify the object that contains the data to be iterated on in the value

attribute.

� The var attribute defines the name of the current object within each

iteration.

� Within the <h:dataTable> the only children allowed are <h:column> elements.

<h:column>

<h:outputText value="#{time.hour}"/>

<f:verbatim>:</f:verbatim>

<h:outputText value="#{time.minute}"/>

<f:verbatim>:</f:verbatim>

<h:outputText value="#{time.second}"/>

</h:column>

� For each column in your table, specify an <h:column> tag.

� Only JSF tags are allowed as children of the <h:column> element.

� <h:outputText> tags are used to access bean properties using JSF

EL syntax.

� Use <f:verbatim> tags to embed literal content.

� <h:outputText> can also be used for literal content, especially if

you are accessing localized data from a resource bundle.

<h:outputText value="literal content"/>

Basic Structure

Page 38: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 123

listPresidents2.jsp<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<html>

<f:view>

<head>

<title>US Presidents</title>

</head>

<body>

<h2>US Presidents</h2>

<h:dataTable value="#{bean.allPresidents}" var="pres">

<h:column>

<h:outputText value="#{pres.id}"/>

</h:column>

<h:column>

<h:outputText value="#{pres.firstName}"/>

</h:column>

<h:column>

<h:outputText value="#{pres.middleName}"/>

</h:column>

<h:column>

<h:outputText value="#{pres.lastName}"/>

</h:column>

</h:dataTable>

</body>

</f:view>

</html>

pres/DataBean.javapackage pres;

public class DataBean {

private static President[] presidents = {

new President(1, "George", "Washington", 1789, 1797),

...

};

...

public President[] getAllPresidents() {

return presidents;

}

}

Try It:Visit http://localhost:8080/DataTable/listPresidents2.faces to see a table of presidents.

Page 39: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 124 Rev 2.1.1 © 2008 ITCourseware, LLC

� Add headers and footers to each column by using the <f:facet> tag as a child of

the <h:column> element.

<h:column>

<f:facet name="header">

<h:outputText value="Description"/>

</f:facet>

<h:outputText value="#{item.description }"/>

</h:column>

� Specify an attribute called name, with a value of header, to embed a

label above the contents of the given column.

� Use a value of footer to add a label below the column.

� Embed an <h:outputText> or <f:verbatim> tag for the contents of the

facet.

Headers and Footers

Page 40: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 125

listPresidents3.jsp<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<html>

<f:view>

<head>

<title>US Presidents</title>

</head>

<body>

<h2>US Presidents</h2>

<h:dataTable value="#{bean.allPresidents}" var="pres">

<h:column>

<h:outputText value="#{pres.id}"/>

</h:column>

<h:column>

<f:facet name="header">

<h:outputText value="First Name"/>

</f:facet>

<h:outputText value="#{pres.firstName}"/>

</h:column>

<h:column>

<f:facet name="header">

<h:outputText value="Middle Name"/>

</f:facet>

<h:outputText value="#{pres.middleName}"/>

</h:column>

<h:column>

<f:facet name="header">

<h:outputText value="Last Name"/>

</f:facet>

<h:outputText value="#{pres.lastName}"/>

</h:column>

</h:dataTable>

</body>

</f:view>

</html>

Try It:Visit http://localhost:8080/DataTable/listPresidents3.faces to see headers added to the table.

Page 41: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 126 Rev 2.1.1 © 2008 ITCourseware, LLC

� JSF HTML tags allow you to use Cascading Style Sheets (CSS) to create a

common look and feel across your web pages.

� You can create a separate file that contains the presentation rules for

particular elements.

� Reference the file with the HTML <link> tag.

<link href="stylesheet.css" rel="stylesheet" type="text/css"/>

� The <h:dataTable> tag can use five different attributes to reference CSS

stylesheet entries.

� The styleClass attribute allows you to specify CSS properties for the

whole table.

� The headerClass and footerClass attributes specify CSS properties for

the table's headers and footers.

� The columnClasses and rowClasses attributes specify CSS properties

for individual rows and columns

Styles

Page 42: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 127

white

light yellow

dark blue

Each row will

alternate applying

even and odd styles.

Note:See http://www.w3.org/TR/REC-CSS1 for more information on Cascading Style Sheets.

stylesheet.css.even {

background: #FFFFFF;

text-align:center;

}

.odd {

background: #FFFFCC;

text-align:center;

}

.presTable {

background: #000099;

}

.presHeader {

color: #FFFFFF;

text-align:center;

}

...

listPresidents4.jsp...

<html>

...

<link href="stylesheet.css" rel="stylesheet" type="text/css"/>

...

<body>

<h2>US Presidents</h2>

<h:dataTable value="#{bean.allPresidents}" var="pres"

styleClass="presTable" headerClass="presHeader"

rowClasses="even, odd">

...

</html>

Try It:Visit http://localhost:8080/DataTable/listPresidents4.faces to see the table with CSS added.

Page 43: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 128 Rev 2.1.1 © 2008 ITCourseware, LLC

� You are not restricted to adding only text content to each column within your

table.

� Any JSF component can be added as a child of <h:column>.

<h:column>

<f:facet name="header">

<h:outputText value="Edit"/>

</f:facet>

<h:selectBooleanCheckbox value="#{theBean.editFlag}"

onclick="this.form.submit()" immediate="true"/>

</h:column>

� These components behave like any other component.

� They can have their own attributes and child elements.

Adding Editable Components

Page 44: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 129

listPresidents5.jsp

...

<html>

...

<h:column>

<f:facet name="header">

<h:outputText value="Edit"/>

</f:facet>

<h:selectBooleanCheckbox value="#{pres.flag}"

onclick="this.form.submit()"/>

</h:column>

<h:column>

<h:outputLink value="#{pres.url}">

<h:outputText value="#{pres.id}"/>

</h:outputLink>

</h:column>

<h:column>

...

<h:inputText value="#{pres.firstName}"

size="12" rendered="#{pres.flag}"/>

<h:outputText value="#{pres.firstName}"

rendered="#{!pres.flag}"/>

</h:column>

...

</html>

pres/President.java

...

public class President {

...

public String getUrl() {

if (url == null) {

String base = "http://en.wikipedia.org/wiki/";

return base + firstName + "_" + lastName;

}

else

return url;

}

public boolean getFlag() {

return flag;

}

...

}

Try It:Visit http://localhost:8080/DataTable/listPresidents5.faces, try clicking on a president's term number. Edit

the first and last name of a president.

Set the flag property to true

or false, depending on the

state of the checkboxes.

Display a text field if

flag=true. Otherwise,

display plain text.

Page 45: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 130 Rev 2.1.1 © 2008 ITCourseware, LLC

� The data table does not actually store all of the data that it renders, it is a view

component.

� It relies on a separate class that inherits from

javax.faces.model.DataModel to serve as the model.

� JSF automatically wraps your data within a DataModel when you use a

data table.

� The type of the DataModel depends upon the original data structure

you've provided to the data table:

� ArrayDataModel

� ListDataModel

� ResultSetDataModel

� ResultDataModel

� ScalarDataModel

� The data table never accesses your data structure directly; it always works with

the corresponding DataModel.

� In your code, you can retrieve the original data structure by calling the

getWrappedData() method on the DataModel.

� This method is often used when adding or removing rows from the

table.

� You can also modify the object that is stored within the DataModel by

calling setWrappedData().

� Sorting techniques typically sort the underlying data structure and

set it back to the DataModel with this method.

DataModel

Page 46: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 131

«abstract»

javax.faces.model

DataModel

javax.faces.model

ScalarDataModel

javax.faces.model

ArrayDataModel

javax.faces.model

ListDataModel

javax.faces.model

ResultDataModel

javax.faces.model

ResultSetDataModel

Page 47: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 132 Rev 2.1.1 © 2008 ITCourseware, LLC

� To sort a table model you need to:

� Create a class that implements Comparator, for each sortable column,

using the compare() method to define the sort order.

� Add an <h:commandLink> to the header of each column that needs to

be sorted.

<h:column>

<f:facet name="header">

<h:commandLink action="#{myBean.sort}"

immediate="true">

<h:outputText value="name"/>

</h:commandLink>

</f:facet>

. . .

</h:column>

� Set the immediate attribute to true because sorting does not

require the full JSF lifecycle to be invoked.

� Bind the link's action attribute to a method that will sort the data based on

the appropriate Comparator object and reset the DataModel with the

new data.

public String sort() {

Arrays.sort(myArray, new Sorter());

dataModel.setWrappedData(myArray);

return null;

}

� Return null, because navigation is not affected by this bound

method.

Sorting

Page 48: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 133

sortPresidents.jsp...

<html>

...

<f:facet name="header">

<h:commandLink action="#{bean2.sortByNumber}"

immediate="true">

<h:outputText value="#"/>

</h:commandLink>

</f:facet>

...

</html>

pres/DataBean2.java...

public class DataBean2 {

...

private NumberSorter numberSorter = new NumberSorter();

private ArrayDataModel arrayModel;

...

public DataModel getAllPresidents() {

if (arrayModel == null)

arrayModel = new ArrayDataModel(presidents);

arrayModel.setWrappedData(presidents);

return arrayModel;

}

...

public String sortByNumber() {

Arrays.sort(presidents, numberSorter);

return null;

}

...

class NumberSorter implements Comparator<President> {

public int compare(President pres1, President pres2) {

Integer id1 = new Integer(pres1.getId());

Integer id2 = new Integer(pres2.getId());

return id1.compareTo(id2);

}

}

}

Try It:Visit http://localhost:8080/DataTable/sortPresidents.faces, click on any header to sort the data in

the table.

Return the

DataModel to

the view.

Reset the DataModel with

the current array.

This Comparator

sorts in ascending

order by id.

Page 49: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 134 Rev 2.1.1 © 2008 ITCourseware, LLC

� When displaying long lists of data within a table, it may be advantageous to add

scrolling behavior.

� Add buttons to allow the user to scroll forward or backward one page at

a time.

� Add buttons to allow the user to skip to the beginning or end of the list.

� The <h:dataTable> element contains two attributes that are used for scrolling.

<h:dataTable "#{myBean.racesTimes}" var="time"

first="#{myBean.firstRowIndex}"

rows="#{myBean.numberOfRowsToDisplay}">

� Use the first attribute to identify which row should be displayed first in

the table.

� The rows attribute identifies how many rows to display.

� Create two properties within your managed bean that represent the index of the

first row to display and the number of rows to display per page.

� Every time the user clicks a navigation button, update the first row index

property to a new value.

public String next() {

firstRowIndex += numberOfRowsToDisplay;

return null;

}

� The data table will automatically display the appropriate rows to the user.

Scrolling

Page 50: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 135

scrollPresidents.jsp...

<html>

...

<h:dataTable value="#{bean3.allPresidents}" var="pres"

first="#{bean3.firstRowIndex}"

rows="#{bean3.numberOfRowsToDisplay}"

styleClass="sortTable" headerClass="sortHeader"

rowClasses="even, odd">

...

</h:dataTable>

<h:commandButton value="First" action="#{bean3.first}"/>

...

<h:commandButton value="Last" action="#{bean3.last}"/>

...

</html>

pres/DataBean3.java...

public class DataBean3 {

private int firstRowIndex = 0;

private int numberOfRowsToDisplay;

...

public int getFirstRowIndex() {

return firstRowIndex;

}

public int getNumberOfRowsToDisplay() {

return numberOfRowsToDisplay;

}

public void setNumberOfRowsToDisplay(int i) {

numberOfRowsToDisplay = i;

}

// scrolling methods

public String first() {

firstRowIndex = 0;

return null;

}

public String last() {

firstRowIndex = arrayModel.getRowCount() - numberOfRowsToDisplay;

if (firstRowIndex < 0) {

firstRowIndex = 0;

}

return null;

}

...

}

The last() method is

bound to the "Last"

command button.

Page 51: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

JavaServer Faces

Page 136 Rev 2.1.1 © 2008 ITCourseware, LLC

� Change the sorting application that was covered in the chapter so that a column will sort in

alternating ascending/descending order when you click it.

(Solutions: Presidents/sortPresidents2.jsp, Presidents/pres/DataBean4.java)

� Change the scrolling application that was presented in the chapter so that the navigation

buttons are disabled when there is no more data to show in either direction.

(Solutions: Presidents/scrollPresidents2.jsp, Presidents/pres/DataBean5.java)

� Modify the scrolling application again so that the user can specify how many rows to scroll

per page.

(Solution: Presidents/scrollPresidents3.jsp)

� Use the files in the starterCode directory for this lab. The current application uses a JSTL

forEach tag to loop through the results of a book search and display each book. Modify

results.jsp to use an <h:dataTable> instead.

(Solution: Books/results2.jsp)

Labs

Page 52: JavaServer Faces - ITCoursewareJavaServer Faces (JSF) brings event-driven, component-based GUI development to the server-side. JSF defines GUI components that are independent of a

Chapter 7 Data Table Component

© 2008 ITCourseware, LLC Rev 2.1.1 Page 137

Note:

Lab � retrieves data from a database. Make sure that the database is running before accessing any JSPs.

To start the Derby database, run startNetworkServer.bat, which can be found under

%DERBY_HOME%\bin.