Documente Academic
Documente Profesional
Documente Cultură
d e
SL-314-EE5 REV C.1
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
D61810GC10
I n
Edition 1.0
D62414
c l e
r a
O
Copyright 2008, 2009, Oracle and/or its affiliates. All rights reserved.
Disclaimer
This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
authorization of Oracle.
The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.
This training manual may include references to materials, offerings, or products that were previously offered by Sun
Microsystems, Inc. Certain materials, offerings, services, or products may no longer be offered or provided.Oracle and its
affiliates cannot be held responsible for any such references should they appear in the text provided.
Trademark Notice
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro
m y
d e
Devices. Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used
under license and are trademarks or registered trademarks of SPARC International, Inc. UNIX is a registered trademark
licensed through X/Open Company, Ltd.
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
This page intentionally left blank.
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
This page intentionally left blank.
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Table of Contents
About This Workbook ............................................................Preface-i
Course Goal ............................................................................. Preface-i
Conventions ............................................................................. Preface-ii
Icons ................................................................................. Preface-ii
Typographical Conventions ......................................... Preface-ii
Additional Conventions.............................................. Preface-iv
Introduction to Web Application Technologies.............................1-1
e A
Task 3 Explore Application Server ...................................... 1-5
Exercise Summary.............................................................................. 1-7
c l
Developing a View Component .......................................................2-1
r a
Objectives ........................................................................................... 2-1
Exercise 1: Designing the Analysis Model for the DVDLibrary
O ly
Application ...................................................................................... 2-2
l & On
Task Design the Analysis Model ......................................... 2-2
Exercise 2: Developing the View Servlet ........................................ 2-3
a e
Task 1 Create the DVDItem Model File................................ 2-4
n
t e r Task 2 Write the ListLibraryServlet View Servlet ..... 2-6
s
Exercise 3: Configuring the Web Application ............................... 2-8
U
Task 1 Verify the View Servlet Configuration................... 2-9
v
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Objectives ........................................................................................... 3-1
Exercise 1: Designing the Analysis Model ..................................... 3-2
Task Design the Analysis Model for the Add a New DVD
Use Case .................................................................................. 3-2
Exercise 2: Developing the Add DVD Form .................................. 3-3
Task 1 Develop the HTML Form ......................................... 3-4
Task 2 Modify the Home Page ............................................. 3-5
Task 3 Deploy the Web Application ................................... 3-5
Task 4 Test the Add DVD Form........................................... 3-6
Exercise 3: Developing a Controller Servlet................................... 3-7
Task 1 Develop the Controller Servlet ................................ 3-7
Task 2 Deploy the Web Application ................................... 3-8
Task 3 Test the AddDVDServlet Servlet ............................. 3-8
Exercise 4: Developing the Success View Servlet.......................... 3-9
Task 1 Modify the Add DVD Controller Servlet............. 3-10
Task 2 Develop the Success View Servlet......................... 3-11
Task 3 Deploy the Web Application ................................. 3-11
Task 4 Test the Web Application ....................................... 3-12
Exercise 5: Developing the Error View Servlet............................ 3-13
Task 1 Modify the Add DVD Controller Servlet............. 3-14
Task 2 Copy the Error View Servlet .................................. 3-15
Task 3 Configure the Error View Servlet.......................... 3-15
Task 4 Deploy the Web Application ................................. 3-15
m y
Task 5 Test the Web Application ....................................... 3-16
d e
c a
Hints................................................................................................... 3-17
Exercise Summary............................................................................ 3-18
A
Developing Dynamic Forms............................................................ 4-1
e
c l
Objectives ........................................................................................... 4-1
Exercise 1: Developing the Add Form View Servlet..................... 4-2
r a
Task 1 Create the AddDVDFormServlet Servlet ................ 4-3
Task 2 Configure the AddDVDFormServlet Servlet .......... 4-5
O ly
Task 3 Remove the Static AddDVD Form.............................. 4-5
Task 4 Modify the Home Page ............................................. 4-5
l & On
Task 5 Deploy the Web Application ................................... 4-6
n a e
Task 6 Test the Web Application ......................................... 4-6
Exercise 2: Displaying Error Information in the Application...... 4-7
t e r U s
Task 1 Modify the AddDVDFormServlet Servlet............... 4-8
Task 2 Modify the AddDVDServlet Servlet........................ 4-8
m y
d e
Designing the Business Tier ...........................................................6-1
Objectives ........................................................................................... 6-1
Exercise 1: Recognizing Model Functionality................................ 6-2
Task Completing the Model Functionality Chart ............. 6-2
c a
A
Exercise 2: Designing a DVDLibrary Service................................. 6-4
Task Drawing the UML Class Diagram.............................. 6-4
e
c l
Exercise 3: Refactoring the Web Application Using the
DVDLibrary Service........................................................................ 6-5
r a
Task 1 Copy the Data File ..................................................... 6-6
O ly
Task 2 Copy Model Components ........................................ 6-6
Task 3 Refactor the InitializeLibrary Context Listener ..
6-7
l & On
Task 4 Refactor the ListLibraryServlet Servlet ........... 6-8
a e
Task 5 Refactor the AddDVDServlet Servlet ...................... 6-8
n
t e r s
Task 6 Modify the Deployment Descriptor........................ 6-9
Task 7 Deploy the Web Application ................................... 6-9
U
I n Task 8 Test the Web Application ....................................... 6-10
Exercise Summary............................................................................ 6-11
vii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Task 3 Verify the Deployment Descriptor.......................... 7-5
Task 4 Deploy the Web Application ................................... 7-6
Task 5 Test the Web Application ......................................... 7-6
Exercise Summary.............................................................................. 7-7
Developing Web Applications Using Session Management........ 8-1
Objectives ........................................................................................... 8-1
Exercise 1: Developing a Session-based Web Application Using
Cookies ............................................................................................. 8-2
Task 1 Add the Set Display Preferences HTML Form...... 8-6
Task 2 Develop the Preferences Action Controller ........... 8-6
Task 3 Configure the SetPreferences Action ................. 8-7
Task 4 Modify the ListLibraryServlet View................ 8-7
Task 5 Deploy the Web Application ................................... 8-8
Task 6 Test the Web Application ......................................... 8-8
Exercise 2 (Advanced): Refactoring the Web Application to Use
URL-Rewriting ................................................................................ 8-9
Task Refactor the Web Application..................................... 8-9
Exercise Summary............................................................................ 8-10
Using Filters in Web Applications.................................................. 9-1
d e
Task 2 Create Data Files ........................................................ 9-6
Task 3 Modify the Web Components.................................. 9-6
c
Task 4 Deploy the Web Application ................................... 9-7 a
Exercise 2 (Advanced): Developing a Compression Filter .......... 9-8
e A
Task 5 Test the Web Application ......................................... 9-7
c l
Task Design a CompressionFilter Class ......................... 9-8
Hints..................................................................................................... 9-9
r a
Exercise Summary............................................................................ 9-10
O ly
Integrating Web Applications With Databases ........................... 10-1
l & On
Objectives ......................................................................................... 10-1
Exercise 1: Starting the DVD Database ......................................... 10-2
n a e
Task 1 Creating the dvdlibrary Database ...................... 10-2
Task 2 Populating the dvdlibrary Database.................. 10-3
t e r U s
Exercise 2: Integrating a Web Application With a Database ..... 10-4
Task 1 Modify the Web Application Components.......... 10-5
A
Exercise Summary.......................................................................... 11-15
e
c l
Developing JSP Pages Using Custom Tags ................................12-1
Objectives ......................................................................................... 12-1
r a
Exercise 1: Refactoring the List Library JSP Page Using the JSTL
Custom Tags .................................................................................. 12-2
O ly
Task 1 Refactor the List Library JSP Page......................... 12-2
Task 2 Deploy the Web Application ................................. 12-3
l & On
Task 3 Test the Web Application ....................................... 12-3
n a e
Exercise 2: Refactoring the Add DVD Form JSP Page Using the
JSTL Custom Tags......................................................................... 12-4
t e r U s
Task 1 Refactor the add_dvd.jsp Page ............................ 12-4
Task 2 Deploy the Web Application ................................. 12-5
ix
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Task 3 Modify the Add DVD Controller .......................... 13-5
Task 4 Modify the Struts Configuration File.................... 13-6
Task 5 Modify the Add DVD Form................................... 13-6
Task 6 Deploy the Web Application ................................. 13-7
Task 7 Test the Web Application ....................................... 13-7
Exercise 2 (Advanced): Using the Struts HTML Tag Library.... 13-8
Task Refactor the AddDVDForm JSP Page .......................... 13-8
Exercise Summary............................................................................ 13-9
Building Reusable Web Presentation Components ................... 14-1
Objectives ......................................................................................... 14-1
Exercise: Building a JSP Page From JSP Fragments .................... 14-2
Task 1 Copy Resources to the Application....................... 14-4
Task 2 Convert the Existing Pages to Segments .............. 14-4
Task 3 Create the Tiles Pages for Each View ................... 14-5
Task 4 Deploy the Web Application ................................. 14-6
Task 5 Test the Web Application ....................................... 14-6
Exercise Summary............................................................................ 14-7
Developing a Basic JavaServer Faces Application ..................A-1
Objectives .......................................................................................... A-1
Exercise 1: Creating a JavaServer Faces Hello World
y
Application ..................................................................................... A-2
m
Task Create a Web Application .......................................... A-2
d e
Preparation................................................................................ A-2
r a
Task 1 Using Cascading Style Sheets (CSS) to Move the
O ly
Locale Links ......................................................................... A-13
Exercise 5: Creating a Layout Navigation for the Application A-14
l & On
Task Set Up Application Navigation ............................... A-14
Exercise 6: Implementing the List Library Feature .................... A-17
a e
Task List the Database User Data ..................................... A-17
n
t e r U s
Exercise Summary........................................................................... A-20
I n
c l e
r a
O
x Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
LabPreface
Course Goal
Upon completion of this lab, you should be able to:
Write servlets using the Java programming language (Java
servlets)
Create robust web applications using Struts, session management,
filters, and database integration
Write pages created with the JavaServer Pages technology (JSP
pages)
m y
Create easy to maintain JSP pages using the Expression Language,
d e
JSP Standard Tag Library (JSTL), and the Struts Tiles framework
Create robust web applications that integrate Struts and JSP pages
c a
e A
Guide.
c l
This workbook presents the lab exercises for each module of the Student
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab Preface-i
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Conventions
Conventions
The following conventions are used in this course to represent various
training elements and alternative learning resources.
Icons
Note Indicates additional information that can help you, but is not
crucial to your understanding of the concepts being described.
Typographical Conventions
Courier is used for the names of commands, files, directories,
programming code, and on-screen computer output; for example:
Use ls -al to list all files.
system% You have mail.
m y
Courier is also used to indicate programming constructs, such as class
d e
names, methods, and keywords; for example:
c a
The getServletInfo method is used to get author information.
e
The java.awt.Dialog class contains Dialog constructor. A
c l
example:
r a
Courier bold is used for characters and numbers that you type; for
O ly
To list the files in this directory, type:
# ls
l & On
n a e
Courier bold is also used for each line of programming code that is
t e r U s
referenced in a textual description; for example:
1 import java.io.*;
I n 2 import javax.servlet.*;
c l e 3 import javax.servlet.http.*;
Notice the javax.servlet interface is imported to allow access to its
life cycle methods (Line 2).
r a
O
Lab Preface-ii Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Conventions
Palatino italics is used for book titles, new words or terms, or words that
you want to emphasize; for example:
Read Chapter 6 in the Users Guide.
These are called class options.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
About This Workbook Lab Preface-iii
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Conventions
Additional Conventions
Java programming language examples use the following additional
conventions:
Method names are not followed with parentheses unless a formal or
actual parameter list is shown; for example:
The doIt method... refers to any method called doIt.
The doIt() method... refers to a method called doIt that takes
no arguments.
Line breaks occur only where there are separations (commas),
conjunctions (operators), or white space in the code. Broken code is
indented four spaces under the starting code.
If a command used in the Solaris Operating System (Solaris OS) is
different from a command used in the Microsoft Windows platform,
both commands are shown; for example:
If working in the Solaris OS:
$cd SERVER_ROOT/BIN
m y
If working in Microsoft Windows:
C:\>CD SERVER_ROOT\BIN
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab Preface-iv Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Lab 1
Objectives
Upon completion of this lab, you should be able to:
Identify web technology characteristics
Explore the GlassFish Application Server (Application Server)
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
1-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Identifying Web Technology Characteristics
This exercise consists of one task, Complete the Web Technologies Chart.
Preparation
No preparation is needed for this exercise.
Servlets
JSP pages
em
Model 2 architecture
a d
Java Platform, Enterprise Edition (Java EE platform)
A c
l e
Complete the following chart. Rate each cell in the table with either poor,
c
good, excellent, or not applicable (N/A). Add comments for situations
r a
that are not easy to evaluate. For example, in the cell for CGI-Script/Easy
to Develop you might note that some scripting languages are easier to
O ly
develop in than others.
l & On
n a e
t e r U s
I n
c l e
r a
O
1-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Identifying Web Technology Characteristics
Robust
Applicat Separation
Fast Cross
Web Technology ion Easy to Develop Scalable of
Execution Platform
Complex Concerns
ity
HTML
CGI script
Servlets only
m y
Model 2
d e
architecture
c a
e A
Java EE platform
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Introduction to Web Application Technologies 1-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Exploring the GlassFish Application Server
Preparation
You must have the following software installed on your system:
GlassFish Application Server
A web browser
m y
d e
Tool Reference Tool references used in this exercise:
c a
Server Resources: Java EE Application Servers: Starting Application
Servers
e A
c l
Server Resources: Java EE Application Servers: Examining Server
Log Files
r a
Server Resources: Java EE Application Servers: Examining
O ly
Application Servers
l & On
n a e
t e r U s
I n
c l e
r a
O
1-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Exploring the GlassFish Application Server
e A
2.
l
Scroll down to the bottom of the log file. You should see a log entry
c
indicating that the Application Server startup was successful.
r a
O Server
Task 3 Explore Application
l y
l & On
a e
In this task, you explore the Application Server Admin Console.
n
e r s
Tool Reference Server Resources: Java EE Application Servers:
t U
Examining Application Servers
I n
c l e Complete the following steps:
1. Launch a web browser and access the Application Server Admin
ra Console.
O
Introduction to Web Application Technologies 1-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Exploring the GlassFish Application Server
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
1-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Introduction to Web Application Technologies 1-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 2
Objectives
Upon completion of this lab, you should be able to develop and deploy a
view component.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
2-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Designing the Analysis Model for the DVDLibrary Application
Figure 2-1 illustrates the use case diagram for the DVDLibrary
application.
m y
This exercise consists of one task, Design the Analysis Model.
d e
Task Design the Analysis Model
c a
e A
case.
c l
As a group, design the Analysis model for the Show List of DVDs use
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
2-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the View Servlet
m y
Selecting the Display my DVD library link produces the List Library page.
Figure 2-3 shows a screen shot of this page.
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
n
Figure 2-3
I
List Library Page Screen Shot
Preparation
No preparation is needed for this exercise.
For this exercise, you first create the DVDLibrary Web Application
project in the project directory, then work in this project for all the
m y
following exercises throughout the course.
d e
Task 1 Create the DVDItem Model File
c a
e A
c l
The DVDItem model component is a class based on the JavaBeans
architecture (JavaBeans class), which represents a single DVDs
a
information: title, year and genre, as shown in Figure 2-4.
r
O ly
DVDItem
-title : String
& On
-year : String
l
-genre : String
constructor
n a e
DVDItem(title:String,
r
year:String,
t
accessors
U s
genre:String)
e
getYear() : String
I n
getTitle() : String
getGenre() : String
r a
O
2-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the View Servlet
e A
l
Location: Source Packages
c
3.
r a
Package: com.dvd.model
Modify the DVDItem class to implement the
O ly
java.io.Serializable interface.
l & On
Tool Reference Java Development: Java Classes: Modifying Java
a e
Classes: Adding Properties
n
4.
t e r U s
Add the following private properties to the DVDItem class and
provide a getter method for each property:
I n String title
e
String year
c l String genre
e A
<th>Title</th>
<th>Year</th>
c l
<th>Genre</th>
</tr>
r a
<tr>
O ly
& On
<td>Star Wars Episode I</td>
l
<td>1999</td>
a e
<td>Sci-Fi</td>
</tr>
<tr>
r n s
n t e U
<td>Close Encounters of the Third Kind</td>
e I <td>1977</td>
<td>Sci-Fi</td>
c l </tr>
<tr>
</tr>
</table>
</body>
</html>
2.
Initialization Parameters: None
Import the following classes in the ListLibraryServlet class:
m y
java.util.List
d e
java.util.Iterator
java.util.ArrayList
c a
3.
com.dvd.model.DVDItem
e A
Within the processRequest method, create a collection of DVDItem
c l
objects, each one representing a DVD in the users DVD collection.
4. r a
(see Hints on page Lab 2-11)
Use print statements to generate the HTML response described at
O ly
the beginning of this task.
5.
& On
Compile the ListLibraryServlet servlet class. Correct any errors
l
a e
you encounter.
n
t e r U s
I n
c l e
r a
O
Developing a View Component 2-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Configuring the Web Application
Figure 2-5 shows the logical URL hierarchy that supports the simple page
flow displayed in Exercise 2: Developing the View Servlet on
page Lab 2-3.
/
index.html
list_library.view
Task 3 Deploy the Web Application
Task 4 Test the ListLibraryServlet Servlet
m y
d e
Preparation
c a
This exercise assumes that the Application Server is installed and
e A
running.
c l
r a
Tool Reference Tool references used in this exercise:
O ly
Java EE Development: Web Modules: Web Deployment Descriptors
l & On
Java EE Development: Web Modules: HTML Files
n a e
Java EE Development: Web Modules: Configuring Web Deployment
t e r
Descriptors: Page Configuration
U s
Java EE Development: Enterprise Application Projects: Building Java
I n
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
e
c l Java EE Applications
r a
O
2-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Configuring the Web Application
m y
Tool Reference Java EE Development: Web Modules: HTML Files
d e
1. Create an HTML file with the following characteristics:
c a
Project: DVDLibrary
e A
c l
HTML File Name: index
Location: Web Pages
2.
r a
Edit the index.html file so that it displays the text, as shown in
O ly
Figure 2-2.
3.
& On
Edit the index.html file to add a link to the List Library page.
l
a e
Tool Reference Java EE Development: Web Modules: Configuring Web
n
4.
t r U s
Deployment Descriptors: Page Configuration
r a
O
Developing a View Component 2-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Configuring the Web Application
d e
2.
http://localhost:8080/dvd/
Click the Display my DVDLibrary link to display the list of DVDs.
c a
3. Debug and resolve any runtime problems you encounter.
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
2-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Hints
Hints
This section provides hints that might help you complete this exercise.
To create a collection, use your favorite java.util.* class.
For example, you can use code similar to:
List dvds = new ArrayList();
dvds.add( new DVDItem(Star Wars Episode I, 1999,
Sci-Fi) );
Use an Iterator to loop over the Collection.
For example:
Iterator it = dvds.iterator();
while(it.hasNext()) {
DVDItem item = (DVDItem) it.next();
out.print(<td>);
out.print(item.getTitle());
out.println(</td);
}
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing a View Component 2-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
2-12 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Lab 3
Objectives
Upon completion of this lab, you should be able to develop and deploy a
controller component that processes HTML form parameters.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
3-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Designing the Analysis Model
Figure 3-1 illustrates the use case diagram for the DVDLibrary
application.
This exercise consists of one task, Design the Analysis Model for the Add
a New DVD Use Case.
m y
d e
Task Design the Analysis Model for the Adda
DVD Use Case
A c a New
c l e
As a group, design the Analysis model for the Add a New DVD use case.
r a
Design a logical web hierarchy for the web application.
O ly
l & On
n a e
t e r U s
I n
c l e
O ra
3-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the Add DVD Form
The page flow starts at the home page. Figure 3-2 shows a screen shot of
this page.
m y
Selecting the Add a DVD to my collection link produces the Add DVD
d e
form. Figure 3-3 shows a screen shot of this page.
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
Figure 3-3 Add DVD Form Screen Shot
c l e
r a
O
Developing a Controller Component 3-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the Add DVD Form
Figure 3-4 shows the logical URL hierarchy that supports the Add a New
DVD use case. This complete hierarchy is implemented incrementally
over the next four exercises. In this exercise, you create the add_dvd.html
form.
/
index.html
list_library.view
add_dvd.html
add_dvd.do
success.view
error.view
d e
Preparation c a
e A
l
This exercise assumes that Application Server is installed and running.
c
r a
Tool Reference Tool references used in this exercise:
O ly
Java EE Development: Web Modules: HTML Files
l & On
Java EE Development: Enterprise Application Projects: Building Java
a e
EE Applications
t e r
Java EE Development: Enterprise Application Projects: Deploying
s
Java EE Applications
U
I
Task 1 n
Develop the HTML Form
c l e
ra
In this task, you develop an HTML form to gather the information to add
a DVD to the application. The information gathered includes the title,
d e
2. Add a link to the Add DVD form in the index.html file.
c a
Task 3 Deploy the Web Application
e A
c l
a
In this task, you build and deploy the DVDLibrary web application.
r
O ly
Complete the following tasks:
1.
& On
Build the DVDLibrary web application. Correct any errors you
l
encounter.
2.
n a e
Deploy the DVDLibrary web application.
t e r U s
I n
c l e
r a
O
Developing a Controller Component 3-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the Add DVD Form
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
3-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Developing a Controller Servlet
Preparation
This exercise assumes that Application Server is installed and running.
Java EE Development: Web Modules: Servlets
Java EE Development: Enterprise Application Projects: Building Java
m y
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
d e
a
Java EE Applications
A c
l e
Task 1 Develop the Controller Servlet
c
r a
Complete the following steps:
1.
O ly
Create a Java servlet with the following characteristics:
& On
Class Name: AddDVDServlet
l
a e
Project: DVDLibrary
n
t e r U s
Location: Source Packages
Package: com.dvd.controller
O
Developing a Controller Component 3-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Developing a Controller Servlet
e A
c
Complete the following steps:l
1.
r a
Refresh the DVDLibrary web application home page.
2.
O ly
Click the link to add a DVD.
3.
& On
Fill in and submit the form.
l
n a e
The response of the web application should indicate that the DVD
was successfully added. However, this is only a message; nothing
e r s
was actually added. You implement this functionality in following
t U
lab exercises.
I n
c l e
r a
O
3-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 4: Developing the Success View Servlet
Submitting the Add DVD form (see Figure 3-3 on page Lab 3-3) responds
with the Success page. Figure 3-5 shows a screen shot of this page. You
should notice the link back to the home page.
m y
Figure 3-5 Add DVD Success Page Screen Shot
d e
c a
The Success view needs the DVDItem object to generate its display. The
A
AddDVDServlet controller servlet must use the request-scope to transmit
e
l
this object. Figure 3-6 illustrates this operation.
c
r a Web Server
O ly Web Container
l & On 1
a e
creates Model
Controller
r n
http://localhost:8080/
dvd/add_dvd.do
s AddDVD 2
DVDItem
e
Library
t U
setAttribute
User 3 forward DVDItem
I n 4
getAttribute
e
Servlet
l
View
Request
ac Success
Preparation
This exercise assumes that the Application Server is installed and
running.
e A
l
a dispatch to the success view servlet.
c
r a
Complete the following steps:
1.
O ly
Open the AddDVDServlet class in the com.dvd.controller
source package.
2.
l & On
Within the doPost method, remove the lines of code that print the
a e
SUCCESS message to the output stream.
n
3.
t e r U s
Store the DVDItem instance created in the request object with the
attribute name dvdItem.
4.
I n
Perform a dispatch to the URL /success.view.
r a
O
3-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 4: Developing the Success View Servlet
3.
from the request object using the attribute name dvdItem.
Use print statements to generate the HTML response, displaying
m y
the information in the DVDItem.
d e
4. Include a hypertext link back to the home page in the HTML
response.
c a
e A
l
Task 3 Deploy the Web Application
c
r a
In this task, you build and deploy the DVDLibrary web application.
O ly
Complete the following steps:
1.
l & On
Build the DVDLibrary web application. Correct any errors you
a e
encounter.
n
2.
t e r s
Deploy the DVDLibrary web application.
U
I n
c l e
r a
O
Developing a Controller Component 3-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 4: Developing the Success View Servlet
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
3-12 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Developing the Error View Servlet
t e r U s
This exercise consists of the following tasks:
I
n Task 1 Modify the Add DVD Controller Servlet
Task 4 Deploy the Web Application
Task 5 Test the Web Application
Preparation
This exercise assumes that the Application Server is installed and
running.
m y
Complete the following steps:
d e
1. Open the AddDVDServlet class in the com.dvd.controller
source package.
c a
2. Within the doPost method, create a List reference called errors
e A
3.
c l
and assign this reference to a new ArrayList.
Perform error checking for each of the request parameters.
4.
r a
If you find an error, add a string to the errors list indicating what
O ly
error was encountered.
& On
For more information, see Hints on page Lab 3-17.
l
5.
a e
Modify the section of code in which the dispatch is performed and
n
check the errors list:
t e r U s
If the errors list is empty, store the DVDItem in the request
object and dispatch to the URL /success.view.
I n
If the errors list is not empty, store the errors list in a request
r a
O
3-14 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Developing the Error View Servlet
d e
3.
Servlet Class: com.dvd.view.ErrorPageServlet
Declare the servlet mapping the ErrorPageServlet servlet with the
c a
following properties:
e A
l
Servlet Name: ErrorPageServlet
c
a
URL Pattern(s): /error.view
r
Task 4 Deploy the WebO y
l
Application
& On
l
a e
In this task, you build and deploy the DVDLibrary web application.
r n s
n t e
Complete the following steps:
U
e I
1. Build the DVDLibrary web application. Correct any errors you
encounter.
ra
O
Developing a Controller Component 3-15
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Developing the Error View Servlet
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
3-16 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Hints
Hints
This section provides hints that might help you complete this exercise.
To dispatch to a view component, create a RequestDispatcher and
use the forward method to perform the dispatch:
RequestDispatcher rd
= request.getRequestDispatcher(page.view);
rd.forward(request,response);
One test of a request parameter might be to see if it is empty:
String paramValue = request.getParameter(paramName);
if( paramValue.trim().length() == 0 ) {
errors.add(ParamName must be supplied);
}
Test a request parameter to see if it is four digits long:
String paramValue = request.getParameter(paramName);
if( ! paramValue.matches(\\d\\d\\d\\d) ) {
errors.add(ParamName must be four digits long);
}
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing a Controller Component 3-17
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
3-18 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Lab 4
Objectives
Upon completion of this lab, you should be able to develop a dynamic
HTML form using servlet technology.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
4-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing the Add Form View Servlet
Figure 4-2 illustrates the new set of genres, which are configured in the
deployment descriptor.
m y
d e
c a
e A
c l
Figure 4-2
r a
Dynamic Genre Drop-Down List
O ly
& On
This exercise consists of the following tasks:
n a e
Task 1 Create the AddDVDFormServlet Servlet
t e r
Task 2 Configure the AddDVDFormServlet Servlet
U s
Task 3 Remove the Static AddDVD Form
I n
Task 4 Modify the Home Page
c l e
Task 5 Deploy the Web Application
Task 6 Test the Web Application
r a
O
4-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing the Add Form View Servlet
Preparation
This exercise assumes that Application Server is installed and running.
A
add_dvd.html form page. This servlet dynamically displays the list of
genres obtained from servlet initialization parameter called genre-list.
e
c l
Complete the following steps:
1.
r a
Create a Java servlet with the following characteristics:
O ly
Class Name: AddDVDFormServlet
l & On
Project: DVDLibrary
a e
Location: Source Packages
n
t e r U s
Package: com.dvd.view
Servlet Name: AddDVDFormServlet
ra
O
Developing Dynamic Forms 4-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing the Add Form View Servlet
e A
a comma.
c l
5.
a
Within the processRequest method, use print statements to
r
generate the HTML form.
O ly
You should use the add_dvd.html static page as a guide to
6.
l & On
implement the processRequest method.
Replace the section that displays the Genre drop-down list with
n a e
values in the genres instance variable.
t e r U s
I n
c l e
r a
O
4-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing the Add Form View Servlet
/
index.html
list_library.view
add_dvd.view
add_dvd.do
success.view
error.view
e
c l
names. You can use the genre list from the static AddDVD form, but
make sure to add a few new genres so that you can see a change in
a
the drop-down list in the web browser.
r
O AddDVD
Task 3 Remove the Static l y Form
l & On
n a e
t e r
Tool Reference Java Development: Other Files: Deleting Files
U s
n
In this task, you delete the add_dvd.html HTML file.
I
c l e
Task 4 Modify the Home Page
ra
O In this task, you modify the Add DVD hyperlink in the home page
index.html to access the dynamic AddDVD form servlet.
c a
Task 1 Modify the AddDVDFormServlet Servlet
e
Task 2 Modify the AddDVDServlet Servlet A
l
a c
Task 3 Remove the ErrorPageServlet Servlet
r
Task 4 Deploy the Web Application
O ly
Task 5 Test the Web Application
l & On
Preparation
n a e
t e r U s
This exercise assumes that Application Server is installed and running.
I n
Tool Reference Tool references used in this exercise:
O
Developing Dynamic Forms 4-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Displaying Error Information in the Application
O ly
AddDVDFormServlet if errors are encountered.
l & On
Complete the following steps:
1.
n a e
Open the AddDVDServlet class in the com.dvd.controller
2.
t r U s
source package.
e
Modify the request dispatcher path from /error.view to
I n
/add_dvd.view in the sections of code that perform the dispatch if
r a
O
4-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Displaying Error Information in the Application
d e
2. Deploy the DVDLibrary web application.
c a
Task 5 Test the Web Application
e A
c l
a
In this task, you test the web application using a web browser.
r
O ly
Complete the following steps:
1.
& On
Refresh the DVDLibrary web application home page.
l
2.
a e
Click the link to add a DVD.
n
3.
t e r
Test the application to see what happens when the form is not filled
s
in correctly.
U
I n
c l e
r a
O
Developing Dynamic Forms 4-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Repopulating Form Data
Preparation
This exercise assumes that Application Server is installed and running.
m y
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications
d e
c a
Task 1 Modify the AddDVDFormServlet Class
e A
c l
In this task, you modify the AddDVDFormServlet to display error
messages.
r a
O ly
Complete the following steps:
1.
l & On
Open the AddDVDFormServlet class in the com.dvd.view source
package.
n a e
2.
t e
data. r
For each form field, repopulate the field using the request parameter
U s
I n
For assistance, see Hints on page Lab 4-12.
c l e
r a
O
4-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Repopulating Form Data
Hints
This section provides some hints to help complete this exercise.
To redisplay a text form element, you can use code similar to:
String paramTitle = request.getParameter("title");
if ( paramTitle == null ) {
paramTitle = "";
}
out.print(" Title: <input type='text' name='title'");
out.print(" value='" + paramTitle + "'>");
out.println("<br/>");
To redisplay a selected option within a select form element, you can
use code similar to:
String paramGenre = request.getParameter("genre");
out.println("Genre: <select name='genre'>");
for ( int i=0; i<genres.length; i++ ) {
out.print("<option");
if ( genres[i].equals(paramGenre) ) {
}
out.print(" selected");
m y
}
out.println(">" + genres[i] + "</option>");
d e
out.println("</select>");
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
4-12 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing Dynamic Forms 4-13
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 5
Objectives
Upon completion of this lab, you should be able to use the context-scope
to share application data across all web application components.
y
2
3
e m
a d
A c
c l e
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
5-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Web Application That Shares Data in a Servlet Context
Web Server
Web Container
listener
Initialize
Library
http://localhost:8080/ creates
dvd/add_dvd.do Servlet
Controller Context
Library
User AddDVD dvdList
m y
e
List
View
a d
0..*
http://localhost:8080/
dvd/list_library.view ListLibrary
A c Model
DVDItem
c l e
Figure 5-1
r a
Architecture Model for This Exercise
O ly
This exercise consists of the following tasks:
l & On
Task 1 Develop the Context Listener
n a e
Task 2 Modify the ListLibraryServlet Servlet
e r s
Task 3 Modify the AddDVDServlet Servlet
t U
I n
Task 4 Verify the Servlet Context Listener Configuration
Task 5 Deploy the Web Application
r a
O
5-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Web Application That Shares Data in a Servlet Context
Preparation
This exercise assumes that Application Server is installed and running.
c l
Class Name: InitializeLibrary
r a
Project: DVDLibrary
O ly
Location: Source Packages
& On
Package: com.dvd.web
l
a e
Interfaces to Implement: Context Listener
n
2.
t e r
Add information to deployment descriptor (web.xml): yes
U s
Edit the contextInitialized method of the
c l e
r a
O
Sharing Application Resources Using the Servlet Contexts 5-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Web Application That Shares Data in a Servlet Context
r a
to the list of DVDs in the context-scope.
O ly
Complete the following steps:
1.
l & On
Open the AddDVDServlet class in the com.dvd.controller
a e
source package.
n
2.
t e r U s
Add code to retrieve the list of DVDs from the context-scope
attribute dvdList.
3.
I n
Add code to add the new DVDItem to the list.
c l e
r a
O
5-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Web Application That Shares Data in a Servlet Context
l
a e
Complete the following steps:
n
1.
2.
t e r U s
Refresh the DVDLibrary web application home page.
Test the application by listing the DVDs in the list, adding a new
ra
O
Sharing Application Resources Using the Servlet Contexts 5-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Using a Resource File to Populate the DVD Collection
Web Server
y
Initialize
Library
e m
d
http://localhost:8080/ creates
Servlet
a
dvd/add_dvd.do
Context
c
Controller
Library
A
User DVDList
AddDVD
c l e List
0..*
http://localhost:8080/
dvd/list_library.view
r a View
ListLibrary
Model
O ly DVDItem
l & On
Figure 5-2
n a eArchitecture Model for This Exercise
t e r U s
I n
c l e
r a
O
5-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Using a Resource File to Populate the DVD Collection
Preparation
This exercise assumes that Application Server is installed and running.
l e
Task 1 Copy the Data File ac
O lyr
l & On
In this task, you copy the data file containing the library of DVDs to the
web application. Each line of this data file contains the title, year, and
a e
genre information of a DVD, delimited by a vertical bar character (|).
n
e r s
Complete the following steps:
t U
I n
Tool Reference Java Development: Other Files: Creating Folders
ra
O
Sharing Application Resources Using the Servlet Contexts 5-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Using a Resource File to Populate the DVD Collection
3.
declaration and instantiation of the list.
Retrieve the library file name from the library-file context
m y
initialization parameter.
d e
4. Use the getRealPath method of the context to get the real path of
the file named by the library-file context initialization parameter.
c a
5. Open a FileInputStream using the file real path obtained in the
e A
previous step.
c l
the IOException.
r a
This should be done in a try-catch block because you need to catch
6.
O ly
Convert the FileInputStream first to an InputStreamReader and
page 5-10).
l & On
the InputStreamReader to a BufferedReader. (see Hints on
7.
n a e
Use the BufferedReader to read each line in this character stream (a
8.
t r U s
single DVD catalog item).
e
Create a DVDItem object using the DVD information parsed from the
I n
line, and store the item in the list.
O
5-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Using a Resource File to Populate the DVD Collection
e A
2.
l
Deploy the DVDLibrary web application.
c
r a
Task 5 Test the Web Application
O ly
& On
In this task, you test the web application using a web browser.
l
a e
Complete the following steps:
n
1.
t e r s
Refresh the DVDLibrary web application home page.
U
I n
2. Test the application by listing the DVDs and verifying that the list
matches the resource file.
c l e
ra
O
Sharing Application Resources Using the Servlet Contexts 5-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Hints
Hints
This section provides hints for completing these exercises.
To read a line at a time from a character stream, wrap the raw
character stream in a BufferedReader object. This class provides the
readLine method.
To split a line into elements, use the String class split method.
For example, to split on the pipe (|) symbol, you could use:
String[] elements = line.split("\\|");
A List is a collection class in the java.util package. A List is an
interface that is implemented by either the LinkedList or
ArrayList class.
To create a new list object:
List l = new ArrayList();
To determine the length of the list:
int len = l.size();
To add a new element into the list:
m y
l.add(item);
d e
To retrieve the nth element of the list:
c a
DVDItem item = (DVDItem) l.get(47);
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
5-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Sharing Application Resources Using the Servlet Contexts 5-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 6
Objectives
Upon completion of this lab, you should be able to recognize model
functionality, design a service component, and refactor a web application
to use that service.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
6-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Recognizing Model Functionality
m y
Which Application
d e
Domain Functionality Model Data Structure Component is This
c
Functionality In a
e A
Displaying the DVD list
c l
A List object holding a
collection of DVDItem
ListLibraryServlet
a
JavaBeans components
r
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
6-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Recognizing Model Functionality
Notes
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Designing the Business Tier 6-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Designing a DVDLibrary Service
This exercise consists of one task, Drawing the UML Class Diagram.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
6-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Refactoring the Web Application Using the DVDLibrary Service
Web Server
Web Container
listener
Initialize my-library.txt
Library
http://localhost:8080/ creates
dvd/add_dvd.do Servlet
Controller Context
Library reads
library
User AddDVD
Model
m y
e
DVDLibrary
http://localhost:8080/
dvd/list_library.view
View
ListLibrary
a d
A c
Figure 6-1
c l e
New DVDLibrary Web Application Architecture
r a
This exercise contains the following sections:
O ly
Task 1 Copy the Data File
l & On
Task 2 Copy Model Components
Task 3 Refactor the InitializeLibrary Context Listener
a e
r n
Task 4 Refactor the ListLibraryServlet Servlet
s
n t e U
Task 5 Refactor the AddDVDServlet Servlet
e I
Task 6 Modify the Deployment Descriptor
Task 7 Deploy the Web Application
l
O r
Designing the Business Tier 6-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Refactoring the Web Application Using the DVDLibrary Service
Preparation
This exercise assumes that Application Server is installed and running.
m y
Note If you have performed this task as part of the earlier advanced lab,
d e
you do not need to do it again.
c a
In this task, you copy the data file containing the library of DVDs to the
e A
c l
web application. Each line of this data file contains the title, year, and
genre information of a DVD, delimited by a vertical bar character (|).
r a
Complete the following steps:
1. O ly
Create a data subdirectory under the WEB-INF directory.
2.
l & On
Copy the my-library.txt file from the resources/context
a e
directory to the WEB-INF/data directory.
n
t e r U s
When the web application is deployed, this library file is located at
the resource path /WEB-INF/data/my-library.txt.
I n
l e
Task 2 Copy Model Components
c
O ra In this task, you copy the DVDLibraryInterface.java file and the
DVDLibrary.java class file from the resources/model directory to
the com.dvd.model source package.
e A
improving it as long as you do not change the interface. In later labs in
c l
this course, you will re-implement the DVDLibrary constructor.
r a
Listener O
Task 3 Refactor the InitializeLibrary
l y Context
l & On
a e
In this task, you refactor the InitializeLibrary context listener to
n
t e r U s
create the DVDLibrary service object rather than the raw DVD list.
I
1.n
Complete the following steps:
Open the InitializeLibrary class in the com.dvd.web source
c l e package.
O 3. Remove the code that creates the DVD list and remove the code that
stores the list in the context-scope.
e A
c l
Task 5 Refactor the AddDVDServlet Servlet
r a
O ly
In this task, you refactor the Add DVD controller servlet to use the
DVDLibrary service component to create the new DVD item.
l & On
a e
Complete the following steps:
n
1.
t e r U s
Open the AddDVDServlet class in the com.dvd.controller
source package.
1.
I n
Add com.dvd.model.DVDLibrary to the imports list.
c l e 2. Remove the code in which you retrieve the DVD list from the
context-scope.
O ra 3.
4.
Remove the code that creates an instance of the DVDItem class.
Add code to retrieve the DVDLibrary object from the context-scope
attribute called library.
5. Use the addDVD method on the DVDLibrary object to create the new
DVD item.
This method also adds that item to the library collection.
e A
c l
For Microsoft Windows, the location is:
C:\student\project\DVDLibrary\web\WEB-INF\data
r n s
Complete the following steps:
1.
n t e U
Build the DVDLibrary web application. Correct any errors you
e I encounter.
ra
O
Designing the Business Tier 6-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Refactoring the Web Application Using the DVDLibrary Service
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
6-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Designing the Business Tier 6-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 7
Objectives
Upon completion of this lab, you should be able to develop a Struts action
class and configure a Struts application.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
7-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Developing a Web Application Using Struts
Web Server
Web Container
my-library.txt
http://localhost:8080/
dvd/add_dvd.do Action AddDVD
Library Servlet Action
User
reads
Model
DVDLibrary
m y
d e
c a
Figure 7-1 DVDLibrary Web Application Using a Struts Architecture
e A
c l
This exercise consists of the following tasks:
r a
Task 1 Develop the Struts Action Controller
O ly
Task 2 Configure the Struts Configuration File
l & On
Task 3 Verify the Deployment Descriptor
n a e
Task 4 Deploy the Web Application
t e r U s
Task 5 Test the Web Application
I n
Preparation
r a
O
7-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Developing a Web Application Using Struts
e A
l
Used Framework: Struts 1.2.9
c
r a
Action Servlet Name: action
Action URL Pattern: *.do
O ly
Application Resources: com.dvd.web.web-app
l & On
Add Struts TLDs: No
n a e
t e r U s
Note The Application Resources property specifies the location of the
Struts application property file. The value com.dvd.web.web-app
I n
corresponds to the web-apps.properties file in the WEB-
INF/classes/com/dvd/web directory. In this exercise, you do not use
c l e this property file. You will use it in Lab 13, Developing Web Applications
Using Struts Action Forms.
r a
O
Developing Web Applications Using Struts 7-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Developing a Web Application Using Struts
e A
4.
l
Copy the code from the doPost method in the AddDVDServlet
c
and paste it into the execute method of AddDVDAction class.
5.
r a
Refactor the code that retrieves the ServletContext object.
O ly
An action object is not a servlet, therefore, you cannot directly call
l & On
the getServletContext method to retrieve the ServletContext
object. However, the Action class provides a method called
a e
getServlet that returns the ActionServlet object. You should
n
6.
t r U s
use this returned servlet object to retrieve the context object.
e
Replace the request dispatch code with code that returns an
I n
appropriate ActionForward object. The next two steps provide
more information.
r a following steps:
a. Use the addDVD method to add the DVD to the collection.
O b. Store the DVDItem in the request attribute dvdItem.
e A
c l
Task 3 Verify the Deployment Descriptor
r a
O ly
In this task, you view the web.xml deployment descriptor to ensure that
the web application is appropriately configured with the Struts
framework.
l & On
n a e
Complete the following steps:
1.
t e r s
Open the web.xml deployment descriptor.
U
I
2.
n Verify the definition and mapping for the Struts ActionServlet
servlet.
r a deleted.
O
Developing Web Applications Using Struts 7-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Developing a Web Application Using Struts
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
7-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing Web Applications Using Struts 7-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 8
Objectives
Upon completion of this lab, you should be able to develop a web
application using session management.
y
2
3
e m
a d
A c
c l e
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
8-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Session-based Web Application Using Cookies
The Set Session Preferences use case allows the user to select which of the
three DVD item fields (title, year, and genre) are shown in the List Library
m y
view. These preferences are stored as session-scoped attributes.
d e
Figure 8-2 shows an Analysis model of the Set Session Preferences use
case. Notice that the SetPrefs boundary component sends the user back
c a
to the home page after setting the preferences. The SetPrefs boundary
e
component has two aspects: an HTML form and a Struts action controller. A
c l
r a
O ly Home
l & On success
The SetPrefs controller will always
Library
User
n a e return the user to the Home page.
t e r U s SetPrefs
n
Figure 8-2
I
Set Preferences Analysis Model
c l e
r a
O
8-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Session-based Web Application Using Cookies
The next three diagrams show the typical page flow of the Set Session
Preferences use case. Figure 8-3 shows the new home page. Notice the
new link to Set user preferences.
Figure 8-4 shows the Set Display Preferences HTML form. This simple
form consists of three related check boxes; one for each field in the List
m y
Library view. The user selects fields and then selects the Set Preferences
button.
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
Figure 8-4 Set Display Preferences Form Screen Shot
c l e
r a The SetPreferences action stores this information in session-scoped
variables and then forwards to the home page (not shown here).
O
Developing Web Applications Using Session Management 8-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Session-based Web Application Using Cookies
Figure 8-5 shows the List Library view. As you can see, the servlet now
uses the user preferences information, from the session attributes, to limit
the fields displayed in the DVD list table.
Figure 8-6 shows the Architecture model of the Set Session Preferences
use case. This model shows the page flow and the components that must
m y
be created. In particular, you need an HTML form (set_prefs.html) and
you need a Struts action class (SetPreferencesAction).
d e
c a
e
Web Server
A
1
c l Web Container
index.html
http://localhost:8080/
dvd/index.html
r a <HTML>
HttpSession
O ly </HTML>
attributes
showTitle=true
2
http://localhost:8080/
l & On showGenre=true
a e
<HTML> success
dvd/set_prefs.html
Library
User
r n s
</HTML>
set attributes
n t e U
set_prefs.html
execute
I
Action SetPreferences
http://localhost:8080/ Servlet Action
l e
dvd/set_prefs.do
c3
r a
O Figure 8-6 Set Preferences Architecture Model
Figure 8-7 shows the new logical web hierarchy for the DVDLibrary web
application.
/
index.html
list_library.view
add_dvd.view
add_dvd.do
success.view
set_prefs.html
set_prefs.do
Task 3 Configure the SetPreferences Action
Task 4 Modify the ListLibraryServlet View
m y
Task 5 Deploy the Web Application
d e
Task 6 Test the Web Application
c a
e A
Preparation
c l
r a
This exercise assumes that Application Server is installed and running.
O ly
Also, your web browser must have cookies enabled.
l & On
Tool Reference Tool references used in this exercise:
n a e
Java Development: Other Files: Copying Files and Folders
t e r U s
Java EE Development: Web Modules: Struts Action Classes
I
n Java EE Development: Web Modules: Web Deployment Descriptors
Java EE Development: Enterprise Application Projects: Building Java
c l e EE Applications
O
Developing Web Applications Using Session Management 8-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Session-based Web Application Using Cookies
m y
1. Create a Struts action class with the following characteristics:
Class Name: SetPreferencesAction
d e
Project: DVDLibrary
c a
Location: Source Packages
e A
l
Package: com.dvd.controller
c
r a
Superclass: org.apache.struts.action.Action
Configuration File: /WEB-INF/struts-config.xml
O ly
Action Path: /set_prefs
l & On
Use ActionForm Bean: No
2.
n a e
Add the javax.servlet.http.HttpSession class to the import list
3.
t r U s
of the SetPreferencesAction class.
e
Within the execute method, complete the following steps:
I n
a. Obtain a reference to the session object.
r a This check box allows for multiple values, therefore you should
m y
2. Declare a forward entry called success that maps to the path to the
home page within the SetPreferencesAction.
d e
c a
Task 4 Modify the ListLibraryServlet View
e A
c l
In this task, you modify the ListLibraryServlet view servlet to use the
table.
r a
users display preferences to restrict the set of columns in the display
O ly
1.
l & On
Complete the following steps:
Open the ListLibraryServlet class in the com.dvd.view
n a e
source package.
1.
t e r s
Obtain a reference to the session object.
U
2.
I n Use the presence or absence of the showTitle, showYear, and
showGenre session-scope attributes to determine which headers (th)
r a
O
Developing Web Applications Using Session Management 8-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Session-based Web Application Using Cookies
e A
c l
preferences, what happens? Why?
What could you change in the current architecture to store the users
a
web site? r
preferences (after they have been set) for subsequent visits to the
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
8-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Refactoring the Web Application to Use URL-Rewriting
Preparation
This exercise assumes that Application Server is installed and running.
Also, your web browser must have cookies disabled.
m y
Task Refactor the Web Application
d e
Complete the following steps:
c a
1.
e A
Turn off cookies in your browser, and then attempt to use the web
application.
c l
r a
You should see that every time you visit the List Library view the
table is empty.
2. O ly
Determine why this is happening and create a solution to mitigate
& On
this problem.
l
n a e
t e r U s
I n
c l e
r a
O
Developing Web Applications Using Session Management 8-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
8-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Lab 9
Objectives
Upon completion of this lab, you should be able to write and configure a
filter.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
9-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Login Filter
In this exercise, you develop a filter to force the user to log in when they
first access the application. The user name from the login is used to
identify the user-specific DVD collection from a data file from a
subdirectory of the directory specified by the data-directory context
parameter of the application. This subdirectory has the same name as the
user name.
Your login filter uses the Basic authentication mechanism that is standard
in the HTTP specification. All web browsers are required to support this
mechanism. Figure 9-1 shows a screen shot of the dialog used by
Netscape v7.0. This dialog allows the user to log in to the web server.
m y
d e
c a
e A
Figure 9-1
c l
Netscape Basic Authentication Dialog Screen Shot
r a
Basic authentication is triggered in the web server when a user attempts
O ly
to access a resource that has been configured to be a secure resource. The
web server checks for a special header, Authorization, which contains
l & On
the users credentials (user name and password) supplied by the web
n a e
browser. If this header does not exist in the request, then the web server
immediately returns an empty response with another header, WWW-
t e r U s
Authenticate, back to the web browser. The browser intercepts that
response and pops-up the authentication dialog (such as the one in
I n
Figure 9-1) to collect the users credentials. After the user selects the OK
button, the web browser sends the original request again but now with
r a
O
9-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Login Filter
Your login filter uses this mechanism to force the user to log in before they
can access the web application. Furthermore, the username part of the
credentials is used to identify the user-specific data file for that persons
DVD collection. The password information is not used.
Web Server
1
http://localhost:8080/ Web Container
dvd/index.html index.html
<HTML> bryan.txt
401 WWW-Auth:Basic
2 2b </HTML>
http://localhost:8080/ retrieves
dvd/index.html
Library Auth:<bryan:nayrb>
User creates library Model
HttpSession
DVDLibrary
2a
3
http://localhost:8080/
dvd/list.view
Auth:<bryan:nayrb>
3a
View
m y
Login
Filter
ListLibrary
d e
c a
Figure 9-2 Login Filter Architecture
e A
c l
In Step 1, the user requests the home page of the application. The login
r a
filter realizes that the user has not logged in yet and responds with a basic
O ly
authentication challenge.
& On
In Step 2, after the user logs in, the web browser resends the original
l
n a e
request with the proper credentials. The login filter uses the username to
create a user-specific DVDLibrary object and store that object in the
t e r U s
session-scope. The login filter then returns the home page as requested.
I n
In Step 3, the user makes a request to the List Library view. The login filter
realizes that the user has already logged in because a session object
c l e already exists for that user. The ListLibrary servlet now uses the library
in the session-scope (as opposed to the context-scope from previous
O
Using Filters in Web Applications 9-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Login Filter
The logic of the login filter is rather complex. Figure 9-3 shows a UML
activity diagram for the logic. There are three possible paths through this
filter, which are highlighted in the diagram with circled step indicators.
These indicators map to the steps in the architecture diagram in Figure 9-2
on page Lab 9-3. Use this diagram as a guide in implementing the logic of
the doFilter method.
LoginFilter
m y
1 2
d e
a
Send an Basic authentication Extract the encoded credentials.
Decode the credentials.
c
challenge back to the browser.
Extract the username.
e A
c l Create the DVDLibrary.
Store the library in the session.
r a
O ly Continue processing the filter chain.
l & On
n a e
t e r U s
I n
Figure 9-3 Login Filter Activity Diagram
c l e
r a
O
9-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Login Filter
Preparation
This exercise assumes that the application server is installed and running.
r a
In this task, you create a filter to audit incoming requests.
O ly
Tool Reference Java EE Development: Web Modules: Filter Classes
l & On
a e
Complete the following steps:
n
1.
t e r U s
Create a filter class with the following characteristics:
Project: DVDLibrary
c l e Package: com.dvd.web
c a
Task 3 Modify the Web Components
e A
c l
r a
In this task, you modify the web components so that each user retrieves
his/her own DVD library from the session-scope.
O ly
& On
Complete the following steps:
l
1.
a e
Open the AddDVDAction class in the com.dvd.controller
n
source package, and modify the class to retrieve the library
2.
t r U s
attribute from the session-scope.
e
Open the ListLibraryServlet class in the com.dvd.view
I n
source package, and modify the class to retrieve the library
c l e 3.
attribute from the session-scope.
Open the InitializeLibrary class in the com.dvd.web source
r a package, and remove the code that stores the "library" attribute in
the context-scope in the InitializeLibrary context listener class.
O
9-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Login Filter
3.
you chose above).
Monitor the log file to see the login messages as you use the
m y
application (see Hints on page Lab 9-9).
d e
4. Terminate the current web browser to test the multi-user aspect of
this program by completing the following steps:
c a
a. Relaunch the browser.
e A
c l
This step eliminates the cached authentication information.
b.
r a
Rerun the application and log in as the other user.
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Using Filters in Web Applications 9-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Developing a Compression Filter
In this exercise, you add a new filter to perform GZIP compression on the
output stream of the response.
d e
The HTTP response header Content-Encoding tells the web
browser that the data stream has been compressed. The string gzip
c a
is a valid value of this header.
e A
c l
You need to wrap a GZIP output stream around the
ServletOutputStream object that is supplied by the
r a
HttpServletResponse object. Therefore, you need to create a
wrapper around the response object before the request is processed
O ly
by the target servlet. Examine the
l & On
javax.servlet.http.HttpServletResponseWrapper class for
more details about this process.
n a e
t e r U s
I n
c l e
r a
O
9-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Hints
Hints
This section provides hints that might help you complete this exercise.
You must cast the ServletRequest passed to the doFilter method
to an HttpServletRequest.
The activity Attempt to retrieve the user credentials from the
request means that you must retrieve the Authorization header
from the HTTP request object.
The activity Send a Basic authentication challenge back to the
browser means that you need to set the HTTP response status code
to 401 and add the WWW-Authenticate header with the value of
Basic realm=dvdLogin. Use the setStatus(int) method in the
HTTP response object to set the status code to 401.
The activity Extract the encoded credentials means that the
Authorization header takes the form Basic <encoded-
credentials> so you need to strip off the first six characters using
the substring method on the String class.
The activity Decode the credentials means that the <encoded-
credentials> must be decoded. The encoding is Base64 and Suns
m y
Java virtual machine (JVM) tool interface includes a special class to
perform this encoding and decoding. The code to decode might look
d e
similar to this:
c a
BASE64Decoder decoder = new BASE64Decoder();
byte[] data = decoder.decodeBuffer(credentials);
e A
l
String pair = new String(data);
c
r a
The BASE64Decoder class is in the sun.misc package.
The activity Extract the username means that the decode
O ly
credentials must be split apart. The decoded credentials take the
l & On
form of <username>:<password> where a colon separates the
username from the password. You can perform this extraction using
a e
the following code:
n
t e r U s
String username = pair.substring(0, pair.indexOf(:));
You can use the getServletContext method of FilterConfig to
c l e
command:
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
9-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Lab 10
Objectives
Upon completion of this lab, you should be able to:
Configure the deployment descriptor to declare a resource reference
Configure the Tomcat server to make a data source available to an
application
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
10-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Starting the DVD Database
Preparation
This exercise assumes that Application Server is installed and running.
Server Resources: Databases: Connecting to Databases
Server Resources: Databases: Executing SQL Queries
m y
d e
Task 1 Creating the dvdlibrary Database
c a
Complete the following steps:
e A
1.
l
Start the Java DB database server if it is stopped.
c
a
To perform this step, use the Tools menu as follows:
r
O ly
Tools > Java DB Database > Start Java DB Server
2.
& On
Open the Create a new Java DB database dialog box.
l
To perform this step, use the Tools menu as follows:
n a e
Tools menu > Java DB Database > Create Java DB Database
e r s
Enter the following properties:
t U
I n
Database Name: dvdlibrary
c l e
User Name: suned
Password: suned
Right click the following database connection and select the Connect
menu option.
a
execute the SQL statements.
r
O ly
l & On
Note Before clicking the Run SQL button, ensure each SQL command
occupies a single line.
n a e
3.
t e
X
r Confirm that the table has been populated with the DVD data.
U s
Tool Reference Server Resources: Databases: Interacting With Database
I n Use the View Data command to see the DVD data in the Item table.
c l e
r a
O
Integrating Web Applications With Databases 10-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Integrating a Web Application With a Database
Web Server
Web Container
Action
Servlet
AddDVD addDVD
Action addDVD
DVDLibrary DVDLibraryDAO
View getDVDLibrary
y
getDVDCollection
Database
ListLibrary
e m
a d
Figure 10-1 DVDLibrary Architecture Using the DAO Pattern
A c
l e
Note There is no coding in this exercise because all of the coding
c
changes are encapsulated behind the model components. From the
r a
perspective of the web components, the application has not changed. This
demonstrates the power of the principle of separation of concerns.
O ly
l & On
This exercise consists of the following tasks:
n a e
Task 1 Modify the Web Application Components
t e r U s
Task 2 Configure the Data Source in the Deployment Descriptor
I n
Task 3 Configure the Data Source in the Application Server
Task 4 Deploy the Web Application
r a
O
10-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Integrating a Web Application With a Database
Preparation
This exercise assumes that Application Server and the Java DB database
server are installed and running.
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
m y
Java EE Applications
d e
Task 1 Modify the Web Application Components c a
e A
c l
In this task, you copy the model resources to the application and modify
a
the LoginFilter class.
r
O ly
Complete the following steps:
1.
& On
Delete the DVDLibrary class from the com.dvd.model source
l
package.
2.
n a e
Copy the DVDLibraryDAO and new DVDLibrary and
t e r U s
DVDLibraryInterface classes from the resources/database
directory to the com.dvd.model source package.
I
3.n Open the LoginFilter class in the com.dvd.web source package.
c l e 4. Remove the line from the LoginFilter class that retrieves the
data-directory context parameter.
r a
O
Integrating Web Applications With Databases 10-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Integrating a Web Application With a Database
e A
3.
c l
Sharing Scope: Shareable
Remove the obsolete items from the deployment descriptor:
a.
r a
Remove the context parameter for the data-directory.
b.
O ly
Remove the InitializeLibrary context listener.
4.
& On
Delete the InitializeLibrary class.
l
n athe Data
e
Server
t e r
Task 3 Configure
U s Source in the Application
I n
c l e In this task, you configure the GlassFish Application Servers Java
Naming and Directory Interface (JNDI) API namespace.
O ra
10-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Integrating a Web Application With a Database
m y
Tool Reference Java EE Development: Configuring Java EE Resources:
Configuring JDBC Resources
d e
2. Create a JDBC Datasource with the following characteristics:
c a
JDBC Connection Pool Name: dvdLibraryPool
e A
l
JNDI Name: jdbc/dvdLibraryDB
c
a
Object Type: User
r
O ly
Enabled: True
& On
3. Open the sun-web.xml deployment descriptor.
4.
l
Verify that resource reference jdbc/dvdLibraryDB used in the web
a e
application is mapped to the JNDI name jdbc/dvdLibraryDB,
r n s
which identifies the JDBC resource you just created.
n t e U
e I
c l
r a
O
Integrating Web Applications With Databases 10-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Integrating a Web Application With a Database
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
10-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Integrating Web Applications With Databases 10-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 11
Objectives
Upon completion of this lab, you should be able to develop JSP pages that
use scripting, standard tags, and basic Expression Language (EL)
expressions.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
11-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Converting the List Library View Component to a JSP Page
Web Server
Web Container
index.html
<HTML>
</HTML>
success
SetPreferences
Action
Action
y
View
Servlet error
m
AddDVD
AddDVDAction Form
success
d e
View View
c a
ListLibrary
e A
Success
c l
r a
Figure 11-1 Current DVDLibrary Architecture
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
11-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Converting the List Library View Component to a JSP Page
Web Server
Web Container
index.html
<HTML>
</HTML>
success
SetPreferences add_dvd.jsp
Action
<%
Action
Servlet error %>
AddDVDAction
success.jsp
list_library.jsp success
<%
<%
%>
%>
m y
d e
Figure 11-2 Current DVDLibrary Architecture
c a
e A
Figure 11-3 shows the logical web hierarchy for this new architecture. The
c l
paths that have changed from xyz.view to xyz.jsp affect links in web
pages as well as in various configuration files.
r a
/
O ly
index.html
l & On
list_library.jsp
n a e
add_dvd.jsp
t e r U s
add_dvd.do
success.jsp
I n set_prefs.html
e
set_prefs.do
r a
O
Developing JSP Pages 11-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Converting the List Library View Component to a JSP Page
In the first exercise, you convert the List Library view to a JSP page.
Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.
Java Development: Other Files: Deleting Files
Java EE Development: Web Modules: Web Deployment Descriptors
m y
Java EE Development: Enterprise Application Projects: Building Java
d e
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
c a
Java EE Applications
e A
c l
Task 1 Convert the List Library Servlet
r a
O ly
In this task, you convert the List Library servlet code into a JSP page.
l & On
Tool Reference Java EE Development: Web Modules: Creating
JavaServer Pages
n a e
t e r U s
Complete the following steps:
1.
I n
Create a JSP page file with the following characteristics:
e A
removed.
c l
definition and mapping for the ListLibraryServlet servlet are
r a
O ly
Task 3 Deploy the Web Application
l & On
In this task, you build and deploy the DVDLibrary web application.
n a e
1.
t r U s
Complete the following steps:
I n encounter.
ra
O
Developing JSP Pages 11-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Converting the List Library View Component to a JSP Page
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
11-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Converting the Add DVD Success View Component to a JSP Page
Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.
a d
Java EE Development: Web Modules: Web Deployment Descriptors
A c
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
c l e
Java EE Development: Enterprise Application Projects: Deploying
r a
Java EE Applications
O Servlet
l y
& On
Task 1 Convert the Success
l
n a e
In this task, you convert the Success servlet code into a JSP page.
t e r U s
Complete the following steps:
I
1.
n Create a JSP file with the following characteristics:
O
Developing JSP Pages 11-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Converting the Add DVD Success View Component to a JSP Page
c a
Complete the following steps:
e A
1.
2.
c l
Open the struts-config.xml file.
Change the path attribute of the success forward tag in the Add
r a
DVD action to point to the JSP page.
O ly
& On
Task 4 Deploy the Web Application
l
n a e
In this task, you build and deploy the DVDLibrary web application.
t e r U s
Complete the following steps:
I
1.n Build the DVDLibrary web application. Correct any errors you
c l e 2.
encounter.
Deploy the DVDLibrary web application.
O ra
11-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Converting the Add DVD Success View Component to a JSP Page
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing JSP Pages 11-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Refactoring the Success JSP Page to Use EL
Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.
c a
Task 1 Refactor the Success JSP Page
e A
c l
standard actions.
r a
In this task, you refactor the Success JSP page to use EL instead of
O ly
& On
Complete the following steps:
l
1.
a e
Open the success.jsp JSP page.
n
2.
3.
t e r
Remove the useBean declaration.
U s
Use EL code to access the DVD item data in the JSP page.
I
4.
n Make a small change to the template text so you can verify that this
new JSP page is working.
c l e
O ra
11-10 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Refactoring the Success JSP Page to Use EL
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing JSP Pages 11-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 4: Converting the Add DVD Form Component to a JSP Page
Preparation
This exercise assumes that the application server and the Derby database
server are installed and running.
a d
Java EE Development: Web Modules: Web Deployment Descriptors
Java EE Development: Enterprise Application Projects: Building Java
A c
EE Applications
c l e
Java EE Development: Enterprise Application Projects: Deploying
r a
Java EE Applications
O ly Servlet
& On
Task 1 Convert the AddDVDFormServlet
l
n a e
In this task, you convert the AddDVDFormServlet code into a JSP page.
t e r U s
Complete the following steps:
I
1.
n Create a JSP file with the following characteristics:
d e
Task 3 Modify the Struts Configurationc a
File
e A
l
In this task, you modify the action forward path for the Success view.
c
r a
Complete the following steps:
1.
O ly
Open the struts-config.xml file.
2.
& On
Change the path attribute of the error forward tag in the Add DVD
l
action to point to the JSP page.
n a e
t e r
Task 4 Deploy s
the Web
U Application
I n
In this task, you build and deploy the DVDLibrary web application.
O encounter.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
11-14 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing JSP Pages 11-15
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 12
Objectives
Upon completion of this lab, and using a combination of EL and JSP
Standard Tag Library (JSTL), you should be able to construct a JSP page
that uses no scriptlet elements.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
12-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Refactoring the List Library JSP Page Using the JSTL Custom Tags
Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.
m y
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
d e
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications c a
e A
c l
Task 1 Refactor the List Library JSP Page
r a
O ly
In this task, you refactor the List Library JSP page to eliminate the
scripting code by using the JSTL custom tag library.
l & On
a e
Complete the following steps:
n
1.
2.
t e r
Open the list_library.jsp page.
U s
Add a taglib directive to include the JSTL core library. This library
I n
uses the Universal Resource Identifier (URI) of
http://java.sun.com/jsp/jstl/core.
r a http://java.sun.com/jsp/jstl/functions.
O 4. Use the JSTL if tag to perform the conditional logic in the JSP page.
5. Use the JSTL length function to retrieve the length of the DVD list.
In the List Library page, the length of the DVD list is shown to the
user. Because the List interface uses the method named size to
return the length of the list, you cannot use EL syntax to retrieve this
value. This is because that method does not adhere to the standard
JavaBeans accessor method rules. Therefore, you need to use an EL
function to retrieve the length of the list. An example of the syntax is
as follows:
You currently have <b>${fn:length(list)}</b> DVDs in
your collection.
In this example, list is a generic variable. You need to decide what
EL code to use to access the DVD list in the session-scope.
d e
2. Deploy the DVDLibrary web application.
c a
Task 3 Test the Web Application
e A
c l
a
In this task, you test the web application using a web browser.
r
O ly
Complete the following steps:
1.
& On
Refresh the DVDLibrary web application home page.
l
2.
a e
Test the application.
n
t e r U s
I n
c l e
r a
O
Developing JSP Pages Using Custom Tags 12-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Refactoring the Add DVD Form JSP Page Using the JSTL Custom Tags
Preparation
This exercise assumes that the application server and the Java DB
database server are installed and running.
m y
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
d e
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications c a
e A
c l
Task 1 Refactor the add_dvd.jsp Page
r a
O ly
In this task, you refactor the add_dvd.jsp page to eliminate the scripting
code by using the JSTL custom tag library.
l & On
a e
Complete the following steps:
n
1.
2.
t e r
Open the add_dvd.jsp page.
U s
Add a taglib directive to include the JSTL core library. This library
I n
uses the URI of http://java.sun.com/jsp/jstl/core.
c l e
r a
O
12-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Refactoring the Add DVD Form JSP Page Using the JSTL Custom Tags
d e
Task 3 Test the Web Application c a
e A
l
In this task, you test the web application using a web browser.
c
r a
Complete the following steps:
1.
O ly
Refresh the DVDLibrary web application home page.
2.
& On
Test the application.
l
n a e
t e r U s
I n
c l e
r a
O
Developing JSP Pages Using Custom Tags 12-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
12-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Lab 13
Objectives
Upon completion of this lab, you should be able to develop ActionForm
components for a flexible Struts application.
y
2
3
e m
a d
A c
c l e
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
13-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Struts Action Form
AddDVD
add_dvd.jsp
<% AddDVDForm AddDVDAction
%>
c a
e
AddDVDForm
A
l
-title : String = null
-year : String = null
a c
-genre : String = null
-newGenre : String = null
O ly
+getTitle() : String
+setYear(year:String)
The accessor methods are
used by the AddDVD action
form bean with the HTML
form parameter data.
l & On
+getYear() : String
+setGenre(genre:String)
+getGenre() : String
class to retrieve the form data
after validation.
n a e +setNewGenre(newGenre:String)
+validate(ActionMapping,
t e r U s
HttpServletRequest)
:ActionErrors
I n
Figure 13-2 The AddDVDForm Component
c l e
r a
O
13-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Struts Action Form
Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.
m y
Java EE Development: Web Modules: Struts ActionForm Beans
Java Development: Java Classes: Modifying Java Classes: Adding
d e
Fields
c a
Java Development: Java Classes: Encapsulating Field
e A
EE Applications
c l
Java EE Development: Enterprise Application Projects: Building Java
r a
Java EE Development: Enterprise Application Projects: Deploying
O ly
Java EE Applications
l
Task 1 Copy the Error
O n
& Messages Properties File
a
n se
t r
In this task, you copy the error messages properties file to your
e U
development environment.
I n
Complete the following steps:
O
Developing Web Applications Using Struts Action Forms 13-3
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Struts Action Form
d e
Location: Source Packages
Superclass: org.apache.struts.action.ActionForm
c a
Configuration File: /WEB-INF/struts-config.xml
e A
Action Path: /add_dvd
c l
2.
a
When the Add DVD form is submitted four input fields values are
r
sent as to the server. The AddDVDForm bean should have an instance
O ly
variable to hold each of the incoming attributes: title, year,
& On
genre, and newGenre.
l
a e
Tool Reference Java Development: Java Classes: Modifying Java
n
a.
t e r
Classes: Adding Fields
U s
Declare each of the instance variables as type String
I n
Tool Reference Java Development: Java Classes: Encapsulating Field
r a
O
13-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Struts Action Form
3. Write the code for the validate method to test the parameters
supplied by the form.
Use the verification code in the AddDVDAction class as your guide
for this step. If you detect an error, add a new ActionMessage to the
errors object.
For example, to test the title parameter, you might use code such
as the following:
if ((title == null) || (title.trim().length() == 0)) {
errors.add(title, new
ActionMessage(error.title.required));
}
4. Add the key name and message text to the web-app.properties file
in the com.dvd.web source package.
m y
Complete the following steps:
d e
1. Open the AddDVDAction class in the com.dvd.controller source
package.
c a
2. Add com.dvd.view.AddDVDForm to the list of imports.
e A
3.
l
In the execute method, remove the code that retrieves the request
parameters.
c
4.
r a
Remove the code that performs validation on the request
O ly
parameters.
5.
& On
Cast the ActionForm passed as an argument to a reference of type
l
AddDVDForm.
6.
n a e
Use the getter methods of the AddDVDForm in the parameters to the
t e r U s
addDVD method on the library object.
I n
c l e
r a
O
Developing Web Applications Using Struts Action Forms 13-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Struts Action Form
Attribute Value
name AddDVDForm
scope request
validate true
m y
input /add_dvd.jsp
d e
4. Compile the AddDVDForm class. Correct any errors you encounter.
c a
Task 5 Modify the Add DVD Form
e A
c l
r a
In this task, you modify the Add DVD form JSP page to use the Struts
error handling tag.
O ly
& On
Complete the following steps:
l
1.
a e
Open the add_dvd.jsp page.
n
2.
t e r U s
Add a tag directive to the page and use
http://struts.apache.org/tags-html as the URI.
3.
I n
Replace the section displaying the errorMsgs array with the errors
tag from the Struts HTML tag library.
c l e
r a
O
13-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Struts Action Form
In this exercise, you refactor the Add DVD form JSP page to use the Struts
HTML form tag library.
This exercise consists of one task, Refactor the AddDVDForm JSP Page.
m y
Discussion Consider the following questions:
d e
?
! Did you notice any difference in the behavior of the Add DVD form
JSP page?
c a
_________________________________________________________
e A
c l
What benefits do you think might be derived from using custom tags
r a
to encode your HTML forms?
_________________________________________________________
O ly
_________________________________________________________
l & On
_________________________________________________________
n a e
t e r U s
I n
c l e
r a
O
13-8 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing Web Applications Using Struts Action Forms 13-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab 14
Objectives
Upon completion of this lab, you should be able to construct a JSP page
with a complex layout, using existing JSP page segments.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
14-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Building a JSP Page From JSP Fragments
Banner
Logo
Body
Side-bar
menu
Copyright
notice
The web designer has created the Tiles layout file and the common
segments, header, navigation menu, and footer. Your job is to create the
content segments from the existing pages and to create the Tiles pages.
Figure 14-2 shows the hierarchy of segment files that is used in the
exercise.
dvd/
WEB-INF/
view/
layout/
mainLayout.jsp
common/
header.jsp
nav.jsp
footer.html
index.jsp
list_library.jsp
add_dvd.jsp
success.jsp
set_prefs.html
m y
Figure 14-2 Protected Hierarchy
d e
This exercise consists of the following tasks:
c a
Task 1 Copy Resources to the Application
e A
c l
Task 2 Convert the Existing Pages to Segments
Task 3 Create the Tiles Pages for Each View
a
r
Task 4 Deploy the Web Application
O ly
Task 5 Test the Web Application
l & On
Preparation
n a e
e r s
This exercise assumes that Application Server and the Derby database
t U
server are installed and running.
I n
c l eTool Reference Tool references used in this exercise:
ra
Java Development: Other Files: Copying Files and Folders
Java Development: Other Files: Creating Folders
d e
4. Copy the common directory from the resources/jsp_reuse
directory to the view directory under the WEB-INF directory.
c a
e A
l
Task 2 Convert the Existing Pages to Segments
c
r a
In this task, you convert the content pages of the current DVDLibrary
O ly
application into JSP segments to be included in the layout page.
l & On
Complete the following steps:
1.
n a e
Copy the content files from the web directory to the view directory.
2.
e r s
Modify each of the files in the view directory:
t U
I n
a.
b.
Open the JSP page.
Remove the <html>, <head>, and <body> tags at the beginning
c l e of each file.
r a c.
d.
Remove the page heading <h1> tags.
Remove the </body> and </html> tags at the end of each file.
O
14-4 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Building a JSP Page From JSP Fragments
3. Create some Welcome User text for the home page and remove the
list of links.
These links exist in the navigation menu.
As an advanced step, consider adding a method called getUser to
the DVDLibrary class, which should return the string name of the
user. You can then use a JSP page for the Home segment to create a
personalized response, such as Welcome, jack, to the DVDLibrary
application.
e A
c.
l
Insert the path to the content-segment file for the home page
c
that you created in Task 2 Convert the Existing Pages to
4. r a
Segments on page Lab 14-4.
Repeat this process for the rest of the views: List Library, Add DVD
O ly
form, Add DVD success, and Set Display Preferences form.
5.
l & On
Open the struts-config.xml file, and set the forward path for
a e
the setPrefs action to index.jsp.
n
6.
t e r
Open the web.xml deployment descriptor, and set the welcome file
s
to index.jsp.
U
I n
c l e
r a
O
Building Reusable Web Presentation Components 14-5
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Building a JSP Page From JSP Fragments
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
14-6 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Building Reusable Web Presentation Components 14-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
m y
d e
ca
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Lab A
Objectives
Upon completion of this lab, you should be able to:
Create a JavaServer Faces application
Create application messages
Localize application messages
Create a layout navigation for the application
m y
This lab is optional. It gives you the opportunity to practice some of the
d e
optional material presented in Appendix G of the Student Guide.
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
A-1
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Creating a JavaServer Faces Hello World Application
Preparation
You must have the following installed on your system:
NetBeans software
GlassFish Application Server
A web browser
m y
This exercise consists of one task, Create a Web Application.
d e
Task Create a Web Application
c a
e A
Complete the following steps.
c l
1.
a
Create a new web application project:
Category: Web r
O ly
Project Type: Web Application
l & On
Project Name: DVDLibrary
a e
Project Location: \export\home\student
n
t e r U s
Framework: JavaServer Faces 1.2
I n
c l e
r a
O
A-2 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Creating a JavaServer Faces Hello World Application
e A
c.
l
Add the getter and setter methods for the username and
c
password properties, as shown above.
r a
O ly
Note In the NetBeans software, right-click one of the Field names. Select
l & On
Refactor and then select Encapsulate Fields. Use the wizard to automate
the creation of the bean.
n a e
3.
t e r U s
Register the new backing bean with the JavaServer Faces application
using the following information.
I n Name: dvd
c l e Class: com.example.model.DVDLibraryBean
Scope: session
Ora You must register the new backing bean in the faces-config.xml
file.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
e
1. The faces-config.xml file can also be found in the Netbeans software by
c l looking under the Configuration Files node in your project under the Netbeans
Project tab, as well as under the Files tab in build /Web/WEB-INF of your
r a projects directory
O 2. You can also add a new managed bean by right-clicking inside the faces-
config.xml file, then choosing JSF->Add Managed Bean.
Note For this lab, the login page is for demonstration purposes only and
does not invoke any actual authentication. The password is ignored, but
the user name is used to retrieve that users data from the database. For
more information about how to program authentication, see the course:
Developing Secure Web-Tier Applications (DTJ-3109).
m y
Location: Web Pages
Folder:
d e
c a
Tool Reference Java EE Development: Web Modules: JavaServer Pages
b.
e A
Copy the contents of the partially completed login.jsp source
file:
c l
r a
/export/home/student/resources/labA_jsf/exercise1/login.jsp
O ly
into the file you created in the previous step.
c.
l & On
Replace the TODO comments with the name of the
appropriate properties from the DVDLibraryBean.
5.
a e
Change the index.jsp file so it shows a welcome message.
n
t e r
a.
U s
Edit the index.jsp file.
I n The index.jsp file is found under the Web Pages node under
the NetBeans Projects tab.
Ora /export/home/student/resources/labA_jsf/exercise1/index.jsp
into the file you created in the previous step.
Note You can rearrange the tags at the end of the web.xml file so they
are more readable. The last view elements, such as the <welcome-file-
list> element, are hard to read because of the formatting of the default
NetBeans software template.
m y
c. Save and close the web.xml file.
d e
7. In the faces-config.xml file, register the navigation rule using the
c a
following information:
e A
From: login.jsp
c l
Outcome Name: home
r a
To: /index.jps
a.
O ly
Open the JavaServer Faces application configuration file,
& On
faces-config.xml, for editing.
l
b.
a e
Register the navigation rule by adding the following XML to
n
the faces-config.xml file.
<navigation-rule>
<from-view-id>
t e r U s
/login.jsp
</from-view-id> I n
l e
<navigation-case>
c
<from-outcome>
r a home
</from-outcome>
O <to-view-id>
/index.jsp
</to-view-id>
</navigation-case>
</navigation-rule>
8. Test the application as it exists to this point.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing a Basic JavaServer Faces Application A-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Creating Application Messages
e
application. For each text message in the application, create a key A
c l
and message in the messages.properties file. For example:
r a
appName=DVD Library
O ly
loginBtnTxt=Login
& On
passwordPrompt=Password:
l
a e
title_home=DVD Library: Home
r n
title_login=DVD Library: Login
s
n t e U
usernamePrompt=User Name:
e Ia.
welcome=Welcome
Add a new properties file.
c l Project: DVDLibrary
O ra Category: Other
Project Type: Properties File
3. Replace the static text with the appropriate value binding expression.
For example, replace the User Name: label with the outputText tag:
<h:outputText value="#{msg.usernamePrompt}"/>
m y
4. Run the application to ensure that the text is replaced properly.
d e
Task 2 Modify the Welcome Message c a
e A
c l
Complete the following steps.
1.
r a
Modify the welcome message in index.jsp to use parameter values:
O ly
<h:outputFormat value="#{msg.welcome}">
<f:param value="#{dvd.username}"/>
& On
<f:param value="#{dvd.password}"/>
l
a e
</h:outputFormat>
2.
n
Replace the welcome text in message.properties with the
r s
n t efollowing:
U
welcome=Welcome {0}! Your password is {1}.
e I
3. Run the application to make sure the parameterized text is replaced
c l properly.
r a
O
Developing a Basic JavaServer Faces Application A-9
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Localizing Application Messages
d e
Note NetBeans software components present both properties files as
c a
included within the same messages.properties node in the Project
e A
(or Files) tree, even though they are two different files in the file system.
c l
follows:
r a
In the German message file, enter the translated string values as
O ly
appName=DVD Bibliothek
& On
loginBtnTxt=Einloggen
l
a e
passwordPrompt=Pa\u00DFwort:
n
t e r U s
title_home=DVD Bibliothek: Hausseite
title_login=DVD Bibliothek: Einloggen
I n usernamePrompt=Nutzername:
c l e a.
welcome=Willkommen {0}! Dien pa\u00DFwort ist {1}
Add a new properties file.
r a Project: DVDLibrary
O Category: Other
e A
d.
l
Use the NetBeans software Fix Imports command to create the
c
needed import statements:
1.
r aRight-click anywhere in the editor window.
2.
O lySelect Fix Imports.
t e r
In the JavaServer Faces application configuration file, faces-
s
config.xml, add a new managed bean, and register the new class
U
using the following information:
I n Name: locale
c l e Class: com.example.view.LocaleBean
r a a.
Scope: session
Open the faces-config.xml file for editing.
O
Developing a Basic JavaServer Faces Application A-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Localizing Application Messages
<managed-bean>
<managed-bean-name>
locale
</managed-bean-name>
<managed-bean-class>
com.example.view.LocaleBean
</managed-bean-class>
<managed-bean-scope>
session
</managed-bean-scope>
</managed-bean>
<application>
<locale>
<locale-config>
<default-locale>
en
y
</default-locale>
<supported-locale>
de
</supported-locale>
em
</locale-config>
a d
</locale>
</application>
A c
5.
l e
Add a new message for each supported language in the
c
messages.properties file:
langEn=English
r a
langDe=Deutsh
O ly
6.
& On
Add components to login.jsp that enable you to switch languages.
l
a e
<h:commandLink immediate="true" action="#{locale.setEn}">
</h:commandLink>
r n
<h:outputText value="#{msg.langEn}"/>
s
t e U
<h:commandLink immediate="true" action="#{locale.setDe}">
n
<h:outputText value="#{msg.langDe}"/>
</h:commandLink>
e I
c l 7. Run the application to ensure that the text is being displayed
properly.
r a
O
A-12 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 4: Localizing Application Messages (Optional)
Note There are several optional tasks and exercises in this course. You
should attempt these exercises only if you have already completed all of
the primary exercises for each module.
O ly
the cascading style sheet file.
& On
<link rel="stylesheet" href="default.css" />
l
Place that link between <f:verbatim> tags, if it appears inside your
a e
<f:view> tags.
r n s
t e U
Note JavaSever Faces technology can overwrite the ID attribute of any
n
e I
HTML tag in the rendered page, therefore you are discouraged from
using HTML ID attributes in your JavaServer Faces page designs.
O
Developing a Basic JavaServer Faces Application A-13
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Creating a Layout Navigation for the Application
m y
d e
c a
e A
c l
Navigational Design Diagram
Figure A-2
r a
Task Set Up Application O y
& On l
Navigation
l
a e
Complete the following steps:
1.
r n s
Add the appropriate message text (and translations) to the messages
n t e properties files.
U
I
...
goToList_library=Display my DVD library
ra
...
O
A-14 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Creating a Layout Navigation for the Application
2. Create JSP page files for each additional file in the Navigation
diagram:
list_library.jsp
add_DVD.jsp
set_prefs.jsp
3. Copy the contents from each appropriate file found in
/export1/syncDTJ/tmp/export/home/student/resources/labA_jsf/exercise4
to the JSP page files that you created in the previous step.
4. Modify the navigation map in the face-config.xml file to add the
navigation paths from index.jsp to the other pages and from the
other page back home, as illustrated in the previous navigational
diagram.
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>home</from-outcome>
<to-view-id>/index.jsp</to-view-id>
</navigation-case>
</navigation-rule>
m y
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
d e
<navigation-case>
<from-outcome>list</from-outcome>
c a
<to-view-id>/list_library.jsp</to-view-id>
</navigation-case>
e A
<navigation-case>
c l
r a
<from-outcome>add</from-outcome>
<to-view-id>/add_DVD.jsp</to-view-id>
</navigation-case>
<navigation-case> O ly
l & On
<from-outcome>prefs</from-outcome>
</navigation-case>
n a e
<to-view-id>/set_prefs.jsp</to-view-id>
</navigation-rule>
t e r U s
I n
c l e
r a
O
Developing a Basic JavaServer Faces Application A-15
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Creating a Layout Navigation for the Application
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
A-16 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 6: Implementing the List Library Feature
This exercise has one task, List the Database User Data.
e A
c
import java.io.*;l
import java.util.ArrayList;
b.
r a
Add a class variable, dvdCollection, to hold a reference to the
O ly
List of the DVDItems belonging to username.
private List dvdCollection = null;
l & On
private DVDLibraryDAO dao = new DVDLibraryDAO();
c.
t e r U
reference to dvdCollection. For safety, if dvdCollection is
s
null, initialize dvdCollection with a call to
dao.getDVDLibrary(username).
I n
public List getDVDCollection() {
l e
if ( this.dvdCollection == null ) {
c this.dvdCollection = dao.getDVDLibrary(username);
r a}
return dvdCollection;
O}
e A
d.
l
Use other table attributes to create a nice table presentation.
c
Example table:
r a
<h:dataTable value="#{dvd.DVDCollection}" var="item" border="0"
cellspacing="0" cellpadding="5">
O ly
<h:column >
l & On
<f:facet name="header">
a e
<h:outputText value="#{msg.column_Title}"/>
n
</f:facet>
e r s
<h:outputText value="#{item.title}"/>
</h:column>
t U
<h:column>
I n
c l e<f:facet name="header">
<h:outputText value="#{msg.column_Year}"/>
a
</f:facet>
O r <h:outputText value="#{item.year}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{msg.column_Genre}"/>
</f:facet>
<h:outputText value="#{item.genre}"/>
</h:column>
</h:dataTable>
5. Add the message text to the message files (messages.properties
and messages_*.properties) for the message text in Steps 3 and 4.
...
welcome_list=You currently have {0} DVDs in your collection."
column_Title=TITLE
column_Year=YEAR
column_Genre=GENRE
...
6. Test by running the application. Log in as user jack. Navigate to the
list library page to see the list of DVD from the database.
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
Developing a Basic JavaServer Faces Application A-19
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary
Exercise Summary
m y
d e
c a
e A
c l
r a
O ly
l & On
n a e
t e r U s
I n
c l e
r a
O
A-20 Web Component Development With Servlet and JSP Technologies
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1