Sunteți pe pagina 1din 188

Web Component Development

with Servlet and JSP


Technologies, Java EE 5
m y
Activity Guide

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.

Sun Microsystems, Inc. Disclaimer

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.

Restricted Rights Notice


If this documentation is delivered to the U.S. Government or anyone using the documentation on behalf of the U.S.
Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS


The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these training materials are
restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

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

Exercise 1: Identifying Web Technology Characteristics ............. 1-2


m y
Objectives ........................................................................................... 1-1

Task Complete the Web Technologies Chart..................... 1-2


Exercise 2: Exploring the GlassFish Application Server .............. 1-4
d e
c a
Task 1 Start Application Server ........................................... 1-5
Task 2 Read Application Server Log File ........................... 1-5

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

I n Task 2 Create the Home Page............................................... 2-9

c l e Task 3 Deploy the Web Application ................................. 2-10


Task 4 Test the ListLibraryServlet Servlet ................ 2-10
Hints................................................................................................... 2-11

r a Exercise Summary............................................................................ 2-12

O Developing a Controller Component ..............................................3-1

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

I n Task 3 Remove the ErrorPageServlet Servlet................ 4-9


Task 4 Deploy the Web Application ................................... 4-9

c l e Task 5 Test the Web Application ......................................... 4-9


Exercise 3: Repopulating Form Data............................................. 4-10

r a Task 1 Modify the AddDVDFormServlet Class................ 4-10


Task 2 Deploy the Web Application ................................. 4-11
O Task 3 Test the Web Application ....................................... 4-11

vi Web Component Development With Servlet and JSP Technologies


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Hints................................................................................................... 4-12
Exercise Summary............................................................................ 4-13
Sharing Application Resources Using the Servlet Contexts .......5-1
Objectives ........................................................................................... 5-1
Exercise 1: Developing a Web Application That Shares Data in a
Servlet Context Attribute ............................................................... 5-2
Task 1 Develop the Context Listener .................................. 5-3
Task 2 Modify the ListLibraryServlet Servlet............. 5-4
Task 3 Modify the AddDVDServlet Servlet........................ 5-4
Task 4 Verify the Servlet Context Listener Configuration5-5
Task 5 Deploy the Web Application ................................... 5-5
Task 6 Test the Web Application ......................................... 5-5
Exercise 2 (Advanced): Using a Resource File to Populate the DVD
Collection ......................................................................................... 5-6
Task 1 Copy the Data File ..................................................... 5-7
Task 2 Modify the Context Listener .................................... 5-8
Task 3 Configure the Context Parameter ........................... 5-9
Task 4 Deploy the Web Application ................................... 5-9
Task 5 Test the Web Application ......................................... 5-9
Hints................................................................................................... 5-10
Exercise Summary............................................................................ 5-11

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

c l e Developing Web Applications Using Struts...................................7-1


Objectives ........................................................................................... 7-1

r a Exercise: Developing a Web Application Using Struts ................ 7-2


Task 1 Develop the Struts Action Controller ..................... 7-3
O Task 2 Configure the Struts Configuration File................. 7-5

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

Exercise 1: Developing a Login Filter.............................................. 9-2


m y
Objectives ........................................................................................... 9-1

Task 1 Develop the Login Filter ........................................... 9-5

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

I n Task 2 Configure the Data Source in the Deployment


Descriptor.............................................................................. 10-6

c l e Task 3 Configure the Data Source in the Application


Server ..................................................................................... 10-6

r a Task 4 Deploy the Web Application ................................. 10-8


Task 5 Test the Web Application ....................................... 10-9
O Exercise Summary.......................................................................... 10-10

viii Web Component Development With Servlet and JSP Technologies


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Developing JSP Pages ...............................................................11-1
Objectives ......................................................................................... 11-1
Exercise 1: Converting the List Library View Component to a JSP
Page ................................................................................................. 11-2
Task 1 Convert the List Library Servlet ............................ 11-4
Task 2 Remove the Old Servlet Code................................ 11-5
Task 3 Deploy the Web Application ................................. 11-5
Task 4 Test the Web Application ....................................... 11-6
Exercise 2: Converting the Add DVD Success View Component to
a JSP Page ....................................................................................... 11-7
Task 1 Convert the Success Servlet.................................... 11-7
Task 2 Remove the Old Servlet Code................................ 11-8
Task 3 Modify the Struts Configuration File.................... 11-8
Task 4 Deploy the Web Application ................................. 11-8
Task 5 Test the Web Application ....................................... 11-9
Exercise 3: Refactoring the Success JSP Page to Use EL ........... 11-10
Task 1 Refactor the Success JSP Page .............................. 11-10
Task 2 Deploy the Web Application ............................... 11-11
Task 3 Test the Web Application ..................................... 11-11
Exercise 4: Converting the Add DVD Form Component to a JSP

Task 1 Convert the AddDVDFormServlet Servlet.......... 11-12


Task 2 Remove the Old Servlet Code.............................. 11-13
m y
Page ............................................................................................... 11-12

Task 3 Modify the Struts Configuration File.................. 11-13


d e
c a
Task 4 Deploy the Web Application ............................... 11-13
Task 5 Test the Web Application ..................................... 11-14

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

I n Task 3 Test the Web Application ....................................... 12-5


Exercise Summary............................................................................ 12-6

c l e Developing Web Applications Using Struts Action Forms ........13-1

r a Objectives ......................................................................................... 13-1


Exercise 1: Developing a Struts Action Form............................... 13-2

O Task 1 Copy the Error Messages Properties File ............. 13-3


Task 2 Create the AddDVDForm Bean ................................. 13-4

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

Exercise 2: Creating Application Messages................................... A-8


Task 1 Modify the Application to Use Messages ............. A-8
c a
A
Task 2 Modify the Welcome Message................................ A-9
Exercise 3: Localizing Application Messages.............................. A-10
e
c l
Task 1 Modify the Application to Use Messages ........... A-10
Exercise 4: Localizing Application Messages (Optional) .......... A-13

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

About This Workbook

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

Courier italics is used for variables and command-line placeholders


that are replaced with a real name or value; for example:
To delete a file, use the rm filename command.

Courier italic bold is used to represent variables whose values are to


be entered by the student as part of an activity; for example:
Type chmod a+rwx filename to grant read, write, and execute
rights for filename to world, group, and users.

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

Introduction to Web Application Technologies

Objectives
Upon completion of this lab, you should be able to:
Identify web technology characteristics
Explore the GlassFish Application Server (Application Server)

Demonstration The demonstration for this lab can be found in the


1 demos/mod01_intro directory.
2
3

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

Exercise 1: Identifying Web Technology Characteristics


In this exercise, you identify web technology characteristics by completing
the chart.

This exercise consists of one task, Complete the Web Technologies Chart.

Preparation
No preparation is needed for this exercise.

Task Complete the Web Technologies Chart


Review the characteristics of the following web technologies:
Hypertext Markup Language (HTML)
Common Gateway Interface (CGI) script
y


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

Complete the following chart:

Robust
Applicat Separation
Fast Cross
Web Technology ion Easy to Develop Scalable of
Execution Platform
Complex Concerns
ity

HTML

CGI script

Servlets only

JSP pages 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

Exercise 2: Exploring the GlassFish Application Server


The GlassFish Application Server is used as the web container for the
exercises in this course. In this exercise, you explore the Application
Server.

This exercise consists of the following tasks:


Task 1 Start Application Server
Task 2 Read Application Server Log File
Task 3 Explore 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

Task 1 Start Application Server


In this task, you start Application Server.

Tool Reference Server Resources: Java EE Application Servers: Starting


Application Servers

Complete the following steps:


1. Start Application Server.
2. Launch a web browser and access the following URL:
http://localhost:8080
You should see the welcome page of Application Server.

Task 2 Read Application Server Log File


In this task, you view the log file of Application Server.

Tool Reference Server Resources: Java EE Application Servers:


m y
Examining Server Log Files
d e
Complete the following steps:
c a
1. View the Application Server log file, server.log.

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

2. Log in to the Application Server Admin Console using the following


credential:
User name: admin
Password: adminadmin
3. Navigate the Admin Console and view different aspects of the
Application Server.
4. Log out of the Application Server Admin Console.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing a View Component

Objectives
Upon completion of this lab, you should be able to develop and deploy a
view component.

Demonstration The demonstration for this lab can be found in the


1 demos/mod02_view directory.
2
3

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

Exercise 1: Designing the Analysis Model for the


DVDLibrary Application
In this exercise, you work as a group to design the Analysis model for the
DVDLibrary application.

Figure 2-1 illustrates the use case diagram for the DVDLibrary
application.

Show list of DVDs

Library Add DVD to list


User

Figure 2-1 DVDLibrary Application Use Case Diagram

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

Exercise 2: Developing the View Servlet


In this exercise, you develop the List Library view servlet. This view
generates a dynamic response by displaying the collection of DVDs to the
user. The page flow starts at the home page. Figure 2-2 shows a screen
shot of this page.

Figure 2-2 DVD Home Page Screen Shot

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

c l e This exercise consists of the following tasks:

r a Task 1 Create the DVDItem Model File


Task 2 Write the ListLibraryServlet View Servlet
O

Developing a View Component 2-3


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the View Servlet

Preparation
No preparation is needed for this exercise.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Creating Web Application
Projects
Java Development: Java Classes: Creating Java Classes
Java Development: Java Classes: Modifying Java Classes: Adding
Properties
Java Development: Java Classes: Modifying Java Classes: Adding
Constructors
Java Development: Java Classes: Modifying Java Classes: Compiling
Java Classes
Java EE Development: Web Modules: Servlets

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

c l e Figure 2-4 The DVDItem Class Diagram

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

Tool Reference Java EE Development: Web Modules: Creating Web


Application Projects

Complete the following steps:


1. Create the DVDLibrary Web Application project with the following
characteristics:
Project Name: DVDLibrary
Project Location: project
Source Structure: Java BluePrints
Server: GlassFish
Java EE Version: Java EE 5
Context Path: /dvd
Set as Main Project: check
Press the Next button and in the ensuing dialog, ensure no
framework is selected. Press the Finish button.

Tool Reference Java Development: Java Classes: Creating Java Classes


m y
2. Create a Java class with the following characteristics:
d e
Class Name: DVDItem
c a
Project: DVDLibrary

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

Ora Tool Reference Java Development: Java Classes: Modifying Java


Classes: Adding Constructors

Developing a View Component 2-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Developing the View Servlet

5. Add a constructor to the DVDItem class with the following


parameters:
String title
String year
String genre
6. Code the constructor to initialize the fields with the parameter
values.

Tool Reference Java Development: Java Classes: Modifying Java


Classes: Compiling Java Classes
7. Compile the DVDItem class. Correct any errors you encounter.

Task 2 Write the ListLibraryServlet View Servlet


In this task, you create a ListLibraryServlet to generate an HTML
response that displays the number of DVDs in the users collection and
their titles. For example, the HTML response might look similar to this:
<html>
<head><title>ListLibraryServlet</title></head>
m y
<body bgcolor=white>
You currently have <b>3</b> DVDs in your
d e
collection:<br>
<table>
c a
<tr>

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>

r a <td>Star Trek 3: The Search for Spock</td>


<td>1984</td>
O <td>Sci-Fi</td>

2-6 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

</tr>
</table>
</body>
</html>

Tool Reference Java EE Development: Web Modules: Servlets

Complete the following steps:


1. Create a Java servlet with the following characteristics:
Class Name: ListLibraryServlet
Project: DVDLibrary
Location: Source Packages
Package: com.dvd.view
Add information to the deployment descriptor (web.xml): Check
Servlet Name: ListLibraryServlet
URL Pattern(s): /list_library.view

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

Exercise 3: Configuring the Web Application


In this exercise, you configure and deploy the List Library view servlet.

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

Figure 2-5 DVDLibrary Logical Web Hierarchy

This exercise consists of the following sections:


Task 1 Verify the View Servlet Configuration
Task 2 Create the Home Page


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

Task 1 Verify the View Servlet Configuration


In this task, you view the web.xml deployment descriptor to verify the
configuration for the DVDLibrary web application.

Tool Reference Java EE Development: Web Modules: Web Deployment


Descriptors

Complete the following steps:


1. Open the web.xml deployment descriptor.
2. View the definition and the mapping for the ListLibraryServlet
servlet, such as the servlet name, servlet class, the URL pattern, and
so on.

Task 2 Create the Home Page


In this task, you create the home page (index.html) for the DVDLibrary
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

eOpen the web.xml deployment descriptor and set index.html as

I n the welcome file.

c l e The web.xml deployment descriptor is located in the WEB-INF


directory of the web application project.

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

Task 3 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Tool Reference Java EE Development: Enterprise Application Projects:


Building Java EE Applications

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.

Tool Reference Java EE Development: Enterprise Application Projects:


Deploying Java EE Applications
2. Deploy the DVDLibrary web application.

Task 4 Test the ListLibraryServlet Servlet


To access the servlet using a web browser, complete the following steps:
m y
1. Launch a web browser and access the following URL:

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing a Controller Component

Objectives
Upon completion of this lab, you should be able to develop and deploy a
controller component that processes HTML form parameters.

Demonstration The demonstration for this lab can be found in the


1 demos/mod03_controller directory.
2
3

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

Exercise 1: Designing the Analysis Model


In this exercise, you work as a group to design the Analysis model for the
DVDLibrary application.

Figure 3-1 illustrates the use case diagram for the DVDLibrary
application.

Show list of DVDs

Library Add DVD to list


User

Figure 3-1 DVDLibrary Application Use Case Diagram

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

Exercise 2: Developing the Add DVD Form


In this exercise, you develop the HTML form for the Add DVD boundary
component.

The page flow starts at the home page. Figure 3-2 shows a screen shot of
this page.

Figure 3-2 DVD Home Page Screen Shot

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

Figure 3-4 DVDLibrary Logical Web Hierarchy

This exercise consists of the following tasks:


Task 1 Develop the HTML Form
Task 2 Modify the Home Page
Task 3 Deploy the Web Application
m y
Task 4 Test the Add DVD Form

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,

O year, and genre for the new DVD.

3-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 Add DVD Form

Complete the following steps:


1. Create an HTML file with the following characteristics:
HTML File Name: add_dvd
Project: DVDLibrary
Location: Web Pages
Folder: None
2. Add a form to add_dvd.html that performs a POST request to the
URL add_dvd.do.
3. Create the form elements to gather the data. Use Figure 3-3 on
page Lab 3-3 as a guide.

Task 2 Modify the Home Page


In this task, you add a hyperlink to the home page to access the Add DVD
form.

Complete the following steps:


m y
1. Open the index.html file.

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

Task 4 Test the Add DVD Form


In this task, you test the web application using a web browser.

Complete the following steps:


1. Launch a web browser and access the DVDLibrary web application
URL:
http://localhost:8080/dvd/
2. Click the link to display 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

Exercise 3: Developing a Controller Servlet


In this exercise, you develop a controller servlet to process the
information passed to the application using the Add DVD form.

This exercise consists the following tasks:


Task 1 Develop the Controller Servlet
Task 2 Deploy the Web Application
Task 3 Test the AddDVDServlet Servlet

Preparation
This exercise assumes that Application Server is installed and running.

Tool Reference Tool references used in this exercise:



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

I n Servlet Name: AddDVDServlet

c l e URL Pattern(s): /add_dvd.do

r a Initialization Parameters: None

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

2. Within the doPost method, create a DVDItem instance using the


parameters in the incoming request.
Do not perform form verification. In Exercise 5: Developing the
Error View Servlet on page Lab 3-13, you modify this servlet to
handle form errors.
3. Use print statements to generate a simple text response, such as
SUCCESS.
In Exercise 4: Developing the Success View Servlet on page Lab 3-9
you will modify this servlet to dispatch to the Success view.

Task 2 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.
m y
d e
Task 3 Test the AddDVDServlet Servlet
c a
In this task, you test the web application using a web browser.

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

Exercise 4: Developing the Success View Servlet


In this exercise, you develop a new view servlet to display the DVD that
has been added. You also modify the controller servlet to dispatch to the
success view servlet after processing the form parameters.

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

O r Figure 3-6 Using the Request Scope

Developing a Controller Component 3-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 4: Developing the Success View Servlet

This exercise consists of the following tasks:


Task 1 Modify the Add DVD Controller Servlet
Task 2 Develop the Success View Servlet
Task 3 Deploy the Web Application
Task 4 Test the Web Application

Preparation
This exercise assumes that the Application Server is installed and
running.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Servlets:
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications
m y
d e
Task 1 Modify the Add DVD Controller Servlet
c a
In this task, you modify the AddDVDServlet controller servlet to perform

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.

c l e For additional information, see Hints on page Lab 3-17.

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

Task 2 Develop the Success View Servlet


In this task, you develop a view servlet to display the information about
the DVD that has been added.

Complete the following steps:


1. Create a Java servlet with the following characteristics:
Class Name: SuccessServlet
Project: DVDLibrary
Location: Source Packages
Package: com.dvd.view
Servlet Name: SuccessServlet
URL Pattern(s): /success.view
Initialization Parameters: None
2. Within the processRequest method, retrieve the DVDItem instance

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

Task 4 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Click the link to add a DVD.
3. Fill in and submit the 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-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

Exercise 5: Developing the Error View Servlet


In this exercise, you modify the controller servlet to dispatch to the Error
Page view when form verification fails. Figure 3-7 shows a screen shot of
the Add DVD form with an error (the year field has been left blank).

Figure 3-7 Add DVD Form With an Error Screen Shot

Figure 3-8 shows a screen shot of the Error Page.


m y
d e
c a
e A
c l
r a
O ly
l & On
Figure 3-8
n a e Error Page Screen Shot

t e r U s
This exercise consists of the following tasks:

I
n Task 1 Modify the Add DVD Controller Servlet

c l e Task 2 Copy the Error View Servlet

r a Task 3 Configure the Error View Servlet


Task 4 Deploy the Web Application
Task 5 Test the Web Application

Developing a Controller Component 3-13


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 5: Developing the Error View Servlet

Preparation
This exercise assumes that the Application Server is installed and
running.

Tool Reference Tool references used in this exercise:


Java Development: Java Classes: Copying Java Classes
Java EE Development: Web Modules: Web Deployment Descriptors
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Modify the Add DVD Controller Servlet


In this task, you modify the AddDVDServlet controller servlet to perform
a dispatch to the success view servlet.

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

c l e attribute called errorMsgs and dispatch to the URL


/error.view.

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

Task 2 Copy the Error View Servlet


In this task, you copy the provided ErrorPageServlet servlet class
from the resources/lab03_controller directory to the
com.dvd.view source package.

Tool Reference Java Development: Java Classes: Copying Java Classes

Task 3 Configure the Error View Servlet


In this task, you configure the Error view servlet in the deployment
descriptor for the DVDLibrary application.

Complete the following steps:


1. Open the web.xml deployment descriptor.
2. Define the ErrorPageServlet with the following properties:
m y
Servlet Name: ErrorPageServlet

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.

c l 2. Deploy the DVDLibrary web application.

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

Task 5 Test the Web Application


In this task, you test the various error conditions by submitting
incomplete forms using a web browser.

Discussion Consider the following questions:


! Why use an error page to show the form verification errors?
?
For usability, what technique works better than an error page to
display verification errors?
What must change in the current application to make that happen?

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing Dynamic Forms

Objectives
Upon completion of this lab, you should be able to develop a dynamic
HTML form using servlet technology.

Demonstration The demonstration for this lab can be found in the


1 demos/mod04_config directory.
2
3

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

Exercise 1: Developing the Add Form View Servlet


In this exercise, you convert the static Add DVD form into a dynamic
view page. The list of genres in the Add DVD form are supplied by
initialization parameters for the servlet. Figure 4-1 illustrates the three
genres from the static HTML form.

Figure 4-1 Static Genre Drop-Down List

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.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Servlets
Java Development: Java Classes: Modifying Java Classes: Adding
Fields
Java Development: Java Classes: Modifying Java Classes: Adding
Methods
Java EE Development: Web Modules: Web Deployment Descriptors
Java Development: Other Files: Deleting Files
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Create the AddDVDFormServlet Servlet m


y
d e
c a
In this task, you create a view servlet that replaces the static

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

I n URL Pattern(s): /add_dvd.view

c l e Initialization Parameters: None

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

Tool Reference Java Development: Java Classes: Modifying Java


Classes: Adding Fields
2. Add a field to the AddDVDFormServlet class with the following
characteristics:
Name: genres
Type: String[]
Access: private
Initial Value: null

Tool Reference Java Development: Java Classes: Modifying Java


Classes: Adding Methods
3. Add a method to the AddDVDFormServlet class with the following
characteristics:
Name: init
Return Type: void
Access: public
Parameters: none
m y
Exceptions: ServletException
d e
4. Within the init method, retrieve the genre-list initialization
c a
parameter. You should use the split method on this value to
populate the genres instance variable. The delimiter of the string is

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

Task 2 Configure the AddDVDFormServlet Servlet


In this task, you configure the dynamic Add DVD form in the deployment
descriptor for the DVDLibrary application. Figure 4-3 shows the new
logical web hierarchy for the application.

/
index.html
list_library.view
add_dvd.view
add_dvd.do
success.view
error.view

Figure 4-3 Logical Web Hierarchy of the DVDLibrary Application

Complete the following steps:


1.
2.
Open the web.xml deployment descriptor.
Add the following initialization parameter to the
m y
AddDVDFormServlet servlet:
Name: genre-list
d e
Value: a comma-delimited list of DVD genre names.
c a
A
The value of the parameter must be a comma-delimited list of genre

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.

Developing Dynamic Forms 4-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing the Add Form View Servlet

Task 5 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 6 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Click the link to add a DVD.
3. Test the application to ensure that everything works as expected.
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-6 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

Exercise 2: Displaying Error Information in the Application


In this exercise, you modify the AddDVDFormServlet to display error
information, if available. You also modify the controller servlet to dispatch
to the AddDVDFormServlet if errors are encountered. Figure 4-4 shows a
screen shot of the dynamic Add DVD form with errors displayed.

Figure 4-4 Add DVD Form With Errors Displayed


m y
d e
This exercise consists the following tasks:

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:

c l e Java Development: Other Files: Deleting Files

ra Java EE Development: Web Modules: Web Deployment Descriptors

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

Java EE Development: Enterprise Application Projects: Building Java


EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Modify the AddDVDFormServlet Servlet


In this task, you modify the AddDVDFormServlet class to display
validation error messages.

Complete the following steps:


1. Open the AddDVDFormServlet class in the com.dvd.view source
package.
2. Within the processRequest method of the AddDVDFormServlet,
retrieve the errorMsgs attribute from the request-scope. The
errorMsgs attribute is a List object, so you need to import the
java.util.List interface.
3. If the errorMsgs attribute is not null, display the strings contained
within the list.
m y
You can use the processRequest method of the
d e
ErrorPageServlet class as a guide to implement the display of
the error messages.
c a
e A
l
Task 2 Modify the AddDVDServlet Servlet
c
r a
In this task, you modify the AddDVDServlet to dispatch to the

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

c l e errors are encountered.

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

Task 3 Remove the ErrorPageServlet Servlet


In this task, you remove the ErrorPageServlet class and its
configuration.

Complete the following steps:


1. Delete the ErrorPageServlet class from the com.dvd.view
source package.
2. Open the web.xml deployment descriptor.
3. Verify that the servlet definition and servlet mapping for
ErrorPageServlet have been removed.

Task 4 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
m y
encounter.

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

Exercise 3: Repopulating Form Data


In this exercise, you modify the AddDVDFormServlet to repopulate the
HTML form so the user does not have to type the information again.

This exercise consists the following tasks:


Task 1 Modify the AddDVDFormServlet Class
Task 2 Deploy the Web Application
Task 3 Test the Web Application

Preparation
This exercise assumes that Application Server is installed and running.

Tool Reference Tool references used in this exercise:


Java EE Development: Enterprise Application Projects: Building Java
EE Applications

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

Task 2 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 3 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Click the link to add a DVD.
3. Test the application to see what happens when the form is not filled
in correctly.
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-11
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Hints

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Sharing Application Resources Using the Servlet


Contexts

Objectives
Upon completion of this lab, you should be able to use the context-scope
to share application data across all web application components.

Demonstration The demonstration for this lab can be found in the


1 demos/mod05_context directory.

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

Exercise 1: Developing a Web Application That Shares


Data in a Servlet Context Attribute
This version of the application stores the DVD list in the context-scope.
You create a context listener that creates the DVD list and places that list
on the context-scope. You also modify the List Library view and Add
DVD controller to use that shared list. Figure 5-1 shows the architecture of
the new DVDLibrary web application.

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

c l e Task 6 Test 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.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Web Application Listeners
Java EE Development: Web Modules: Web Deployment Descriptors
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Develop the Context Listener


In this task, you create a context listener that creates the DVD list and
stores that list in the context-scope.

Tool Reference Java EE Development: Web Modules: Web Application


m y
Listeners
d e
Complete the following steps:
c a
1.
e A
Create a web application listener with the following characteristics:

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

I n InitializeLibrary listener class as follows:


a. Create a List object (see Hints on page 5-10).

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

b. Populate the list with DVDItem objects.


You can use the code that creates and populates the dvds list in
the ListLibraryServlet class, but make sure to add a few
new DVDs to the list so that you can ensure that your
application is working correctly.
c. Store the list in the context-scope in an attribute called
dvdList.
3. Leave the contextDestroyed method empty.

Task 2 Modify the ListLibraryServlet Servlet


In this task, you modify the ListLibraryServlet servlet to display the
list of DVDs from the context-scope.

Complete the following steps:


1. Open the ListLibraryServlet class in the com.dvd.view
source package.
2. Remove the code that creates the local DVD list.
m y
3. Add code to retrieve the DVD list from the context-scope attribute
dvdList.
d e
c a
Task 3 Modify the AddDVDServlet Servlet
e A
c l
In this task, you modify the AddDVDServlet servlet to add the new DVD

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

Task 4 Verify the Servlet Context Listener


Configuration
In this task, you verify the web.xml deployment descriptor to ensure that
the web application listener is appropriately configured.

Complete the following steps:


1. Open the web.xml deployment descriptor.
2. Verify that the InitializeLibrary web application context
listener class is defined in the deployment descriptor, and the listener
class is com.dvd.web.InitializeLibrary.
The listener element of the deployment descriptor is used to
define web application listeners. The listener class is defined in the
listener-class child element of the listener element.

Task 5 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.
m y
Complete the following steps:
d e
1. Build the DVDLibrary web application. Correct any errors you
encounter. c a
2.
e
Deploy the DVDLibrary web application. A
c l
r a
Task 6 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.
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

I n DVD to the list, and then viewing the list again.

c l e The new entry should appear in the second list.

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

Exercise 2 (Advanced): Using a Resource File to Populate


the DVD Collection

Note This is an advanced exercise. Only attempt this exercise if you


have completed Exercise 1: Developing a Web Application That Shares
Data in a Servlet Context Attribute on page 5-2. You are not required to
complete this exercise.

This version of the application has the InitializeLibrary context


listener construct the list of DVDs from a resource file in the web
application. Figure 5-2 shows the architecture of the new DVDLibrary
application.

Web Server

Web Container my-library.txt


listener
reads

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

This exercise consists the following tasks:


Task 1 Copy the Data File
Task 2 Modify the Context Listener
Task 3 Configure the Context Parameter
Task 4 Deploy the Web Application
Task 5 Test the Web Application

Preparation
This exercise assumes that Application Server is installed and running.

Tool Reference Tool references used in this exercise:


Java Development: Other Files: Creating Folders
Java Development: Other Files: Copying Files and Folders
Java EE Development: Web Modules: Web Deployment Descriptors
y

Java EE Development: Web Modules: Web Deployment Descriptors:


General Configuration: Context Parameters
e m
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
a d
Java EE Development: Enterprise Application Projects: Deploying
A c
Java EE Applications

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

c l e 1. Create a data subdirectory under the WEB-INF directory.

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

Tool Reference Java Development: Other Files: Copying Files and


Folders
2. Copy the my-library.txt file from the resources/context
directory to the WEB-INF/data directory:
When the web application is deployed, this library file is located at
the resource path /WEB-INF/data/my-library.txt.

Task 2 Modify the Context Listener


In this task, you modify the InitializeLibrary context listener to
retrieve the DVD list from a flat-file data source.

Complete the following steps:


1. Open the InitializeLibrary class in the com.dvd.web source
package.
2. Remove the code that created the list of DVD items, but keep the

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.

c l e 9. Ensure that the DVD list is stored in the context-scope.


10. Close all streams.

r a This is done in the finally clause of the try-catch block.

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

Task 3 Configure the Context Parameter


In this task, you modify the deployment descriptor to declare the context
initialization parameter.

Complete the following steps:


1. Open the web.xml deployment descriptor.

Tool Reference Java EE Development: Web Modules: Web Deployment


Descriptors: General Configuration: Context Parameters
2. Create the following context parameter for the DVDLibrary web
application:
Parameter Name: library-file
Parameter Value: /WEB-INF/data/my-library.txt

Task 4 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.
m y
Complete the following steps:
d e
1. Build the DVDLibrary web application. Correct any errors you
c a
encounter.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Designing the Business Tier

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.

Demonstration The demonstration for this lab can be found in the


1 demos/mod06_model directory.
2
3

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

Exercise 1: Recognizing Model Functionality


In this exercise, you work as a group to analyze the current DVDLibrary
application to identify functionality that belongs in the model.

This exercise consists of one task, Completing the Model Functionality


Chart.

Task Completing the Model Functionality Chart


As a group, discuss the features of the web application that are domain-
specific. As an example, the first entry in the table is provided for you.
The domain-specific functionality is Displaying the DVD list. The
Model data structure that performs this functionality is a List object
holding a collection of DVDItem JavaBeans components. The web
application component that supports that functionality is the
ListLibraryServlet view component.

Complete the following chart.

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

Exercise 2: Designing a DVDLibrary Service


In this exercise, you work as a group to design the DVDLibrary service
component.

This exercise consists of one task, Drawing the UML Class Diagram.

Task Drawing the UML Class Diagram


As a group, design the DVDLibrary service component based on the
functional requirements identified in the previous exercise. Use the space
below to draw the Unified Modeling Language (UML) class diagram for
this design.

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

Exercise 3: Refactoring the Web Application Using the


DVDLibrary Service
Figure 6-1 shows the new architecture of the DVDLibrary web
application. Notice that web components access the DVD list through the
DVDLibrary service component. This Model component also hides the
implementation details of using a flat-file data source.

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

a c Task 8 Test the Web Application

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.

Tool Reference Tool references used in this exercise:


Java Development: Java Classes: Copying Java Classes
Java Development: Other Files: Creating Folders
Java Development: Other Files: Copying Files and Folders
Java EE Development: Web Modules: Web Deployment Descriptors:
General Configuration: Context Parameters
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Copy the Data File

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.

6-6 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

The public interface described by DVDLibraryInterface.java is quite


simple. It declares only four methods:
getDVDColletion Returns a read-only reference the
Collection of DVDs in the library.
addDVD Given a title, a year and a genre, this method creates a
new DVD item, adds it to the library, and returns a reference to
the new DVD item.
getGenre Returns a read-only reference the List of genres
currently recognized by the library
addGenre Given the name of a genre, checks if that genre is
already in the current genre list, and if not adds the new genre
to the list.

You may review the implementation of the DVDLibrary class. The


DVDLibrary class requires knowledge of the location of the my-
library.txt that you copied into your project in the previous task. This
location information is passed to the DVDLibrary class as a constructor
parameter. The DVDLibrary class calls a private method to load the DVD
items from the flat-file data store, with the hard-code name my-
library.txt, found in the directory location. The DVD items are stored
m y
in a private Collection object. The genre list is initialized with a few hard-
coded values in the DVDLibrary constructor.
d e
Clearly, this implementation can be improved. And if you feel you have
c a
time in class, after you complete this lab, you may experiment with

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.

ra 2. Add com.dvd.model.DVDLibrary to the imports list.

O 3. Remove the code that creates the DVD list and remove the code that
stores the list in the context-scope.

Designing the Business Tier 6-7


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Refactoring the Web Application Using the DVDLibrary Service

4. Add code to retrieve a context initialization parameter, called data-


directory, and create a DVDLibrary object using the value of this
attribute as the parameter of the DVDLibrary constructor.
5. Add code to store the created DVDLibrary object in the context-
scope, under the attribute called library.
6. Add code to log the fact that the library object was initialized.

Task 4 Refactor the ListLibraryServlet Servlet


In this task, you refactor the List Library view servlet to use the
DVDLibrary service component rather than the raw DVD list.

Complete the following steps:


1. Open the ListLibraryServlet class in the com.dvd.view
source package.
2. Add com.dvd.model.DVDLibrary to the imports list.
3. Remove the code in which you retrieve the DVD list from the
context-scope.
m y
4. Add code to retrieve the DVDLibrary object from the context-scope
attribute called library.
d e
5. Use the getDVDCollection method on the DVDLibrary object to
c a
retrieve the DVD list.

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.

6-8 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

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.

Task 6 Modify the Deployment Descriptor


In this task, you modify the web.xml deployment descriptor to define the
data-directory context parameter.

Complete the following steps:


1. Open the web.xml deployment descriptor.
2. If you completed Exercise 2 (Advanced): Using a Resource File to
Populate the DVD Collection on page Lab 5-6, then remove the
context initialization parameter called library-file.
3. Create the following context parameter for the DVDLibrary web
application:
Parameter Name: data-directory
Parameter Value: deployed location of my-library.txt
m y
The fully qualified path for the deployed location of the my-
d e
library.txt file for Solaris OS is:
/export/home/student/project/DVDLibrary/web/WEB-
c a
INF/data

e A
c l
For Microsoft Windows, the location is:
C:\student\project\DVDLibrary\web\WEB-INF\data

Task 7 Deploy the WebO


r a
l y
Application
& On
l
a e
In this task, you build and deploy the DVDLibrary web application.

r n s
Complete the following steps:
1.
n t e U
Build the DVDLibrary web application. Correct any errors you

e I encounter.

c l 2. Deploy the DVDLibrary web application.

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

Task 8 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the application by listing the DVDs in the collection and adding
DVDs to the collection.
Every time you add a new DVD, The DVDLibrary service
component appends the information of the new DVD to the flat-file
data store. Therefore, when you redeploy the web application,
previously added DVDs will not be lost.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing Web Applications Using Struts

Objectives
Upon completion of this lab, you should be able to develop a Struts action
class and configure a Struts application.

Demonstration The demonstration for this lab can be found in the


1 demos/mod07_struts directory.
2
3

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

Exercise: Developing a Web Application Using Struts


In this exercise, you modify the DVDLibrary web application to use the
Struts Model-View-Controller (MVC) framework. The changes to the
existing architecture are fairly small. In terms of code, you convert the
AddDVD controller servlet into a Struts action class. Beyond that, you only
need to make configuration changes, no other code is affected. Figure 7-1
shows this new architecture.

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

c l e This exercise assumes that Application Server is installed and running.

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

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Adding Frameworks
Java EE Development: Web Modules: Struts Action Classes
Java Development: Other Files: Deleting Files
Java EE Development: Web Modules: Web Deployment Descriptors
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Develop the Struts Action Controller


In this task, you convert the AddDVDServlet controller from a servlet
into a Struts action class.

Tool Reference Java EE Development: Web Modules: Web Application


Frameworks: Adding Frameworks
m y
Complete the following steps:
d e
1. Add the Struts Framework support to the DVDLibrary web
c a
application project with the following properties:

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

Tool Reference Java EE Development: Web Modules: Struts Action


Classes: Creating Struts Action Classes
2. Create a Struts action class with the following characteristics:
Class Name: AddDVDAction
Project: DVDLibrary
Location: Source Packages
Package: com.dvd.controller
Superclass: org.apache.struts.action.Action
Configuration File: /WEB-INF/struts-config.xml
Action Path: /add_dvd
Use ActionForm Bean: No

Note In this exercise, you do not use a Struts ActionForm bean to


validate user input, therefore, the AddDVDAction class does not need to
have a form bean. You use a form bean to implement the input validation
in Lab 13, Developing Web Applications Using Struts Action Forms.
m y
You should use the code in AddDVDServlet as your guide for the
d e
3.
following steps.
Open the AddDVDServlet class in the com.dvd.controller
c a
source package.

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.

c l e 7. If no errors are present in the submitted form, complete the

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.

7-4 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

c. Locate the ActionForward object named success in the


ActionMapping object. Return this object from the execute
method.
8. If errors are present, complete the following steps:
a. Store the error list in the request attribute errorMsgs.
b. Locate the ActionForward object named error in the
ActionMapping object. Return this object from the execute
method.
9. Delete the AddDVDServlet servlet class.

Task 2 Configure the Struts Configuration File


In this task, you configure the Struts action object that you just created.

Complete the following steps:


1. Open the Struts configuration file struts-config.xml.
The struts-config.xml is located in the WEB-INF directory of
the web application project.
m y
2. Declare two forward entries within the /add_dvd action:
d e
a. Declare the forward success with the path /success.view.
c a
b. Declare the forward error with the path /add_dvd.view.

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.

c l e 3. Verify that the definition and mapping for AddDVDServlet is

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

Task 4 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 5 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the application by listing the DVDs in the collection and adding
DVDs to the collection.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing Web Applications Using Session


Management

Objectives
Upon completion of this lab, you should be able to develop a web
application using session management.

Demonstration The demonstration for this lab can be found in the


1 demos/mod08_sessions directory.

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

Exercise 1: Developing a Session-based Web Application


Using Cookies
In this exercise, you add a new use case to the DVDLibrary application.
Figure 8-1 shows the new set of use cases.

DVD Library Application

Show list of DVDs

Add DVD to list


Library
User
Set session preferences

Figure 8-1 DVDLibrary Use-Case Diagram

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-3 Home Page Screen Shot

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-5 List Library View Screen Shot

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

8-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 Session-based Web Application Using Cookies

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

Figure 8-7 DVDLibrary Logical Web Hierarchy

This exercise consists of the following tasks:


Task 1 Add the Set Display Preferences HTML Form
Task 2 Develop the Preferences Action Controller


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

r a Java EE Development: Enterprise Application Projects: Deploying


Java 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

Task 1 Add the Set Display Preferences HTML Form


Complete the following steps:
1. Copy the set_prefs.html file from the resources/sessions
directory to the Web Pages section of the DVDlibrary project in the
web directory.
2. Modify the index.html home page to include a link to the Set
Display Preferences form.

Task 2 Develop the Preferences Action Controller


In this task, you develop the SetPreferencesAction class that processes
the Set Display Preferences HTML form.

Complete the following steps:

Tool Reference Java EE Development: Web Modules: Struts Action


Classes: Creating Struts Action Classes

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.

c l e b. Retrieve the values associated with the request parameter called


show.

r a This check box allows for multiple values, therefore you should

O use the getParameterValues method. This method returns a


string array.

8-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 Session-based Web Application Using Cookies

c. If showTitle exists in the values associated with the request


parameter show, assign the string true to the session attribute
showTitle; otherwise, remove the session attribute.
d. If showYear exists in the values associated with the request
parameter show, assign the string true to the session attribute
showYear; otherwise, remove the session attribute.
e. If showGenre exists in the values associated with the request
parameter show, assign the string true to the session attribute
showGenre; otherwise, remove the session attribute.
f. Return the ActionForward identified by the string success.

Task 3 Configure the SetPreferences Action


In this task, you configure the SetPreferences action in the Struts
configuration file.

Complete the following steps:


1. Open the struts-config.xml file.

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)

c l e and columns of data (td) to display.

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

Task 5 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 6 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the application by modifying preferences and listing the DVDs
in the collection.
You should change the preferences several times in different
m y
combinations to make sure the code is working correctly.
d e
Discussion Consider the following:
c a
?
! If you try to list the DVDs in your collection before setting your

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

Exercise 2 (Advanced): Refactoring the Web Application to


Use URL-Rewriting

Note This is an advanced exercise. Only attempt this exercise if you


have completed Exercise 1: Developing a Session-based Web Application
Using Cookies on page Lab 8-2. You are not required to complete this
exercise.

In this exercise, you modify the web application to use URL-rewriting.


The goal is to make the web application work without cookies.

This exercise consists of one task, Refactor the Web Application.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Using Filters in Web Applications

Objectives
Upon completion of this lab, you should be able to write and configure a
filter.

Demonstration The demonstration for this lab can be found in the


1 demos/mod09_filters directory.
2
3

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

Exercise 1: Developing a Login Filter


A significant limitation of the current DVDLibrary web application is
that there is only one library. Every user of the application views and
manipulates the same collection of DVDs. To make this application more
robust, the library object must be unique to a given user. There are many
ways of achieving this goal.

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

c l e the Authorization header.

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.

Figure 9-2 shows the architecture of the login filter.

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

r a exercises) to generate the DVD list display.

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

Cast the request and response


objects to the HTTP interfaces.

Attempt to retrieve the library


attribute from the session scope.

[else] [library == null]


3

Continue processing Attempt to retrieve the user


the filter chain. credentials from the request.

[credentials == null] [else]

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

This exercise consists of the following tasks:


Task 1 Develop the Login Filter
Task 2 Create Data Files
Task 3 Modify the Web Components
Task 4 Deploy the Web Application
Task 5 Test the Web Application

Preparation
This exercise assumes that the application server is installed and running.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Filter Classes
Java Development: Other Files: Creating Folders
Java Development: Other Files: Creating New Files
y

Java EE Development: Enterprise Application Projects: Building Java


EE Applications
e m
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications
a d
A c
c l e
Task 1 Develop the Login Filter

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

I n Class Name: LoginFilter

c l e Package: com.dvd.web

r a Location: Source Packages


Filter Name: LoginFilter
O Applies To: /*
Initialization Parameters: None

Using Filters in Web Applications 9-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Developing a Login Filter

2. Add your business logic to the doFilter method.


You should use the activity diagram, Figure 9-3 on page Lab 9-4, as
your guide (see Hints on page Lab 9-9). You should use the
ServletContext log method to record the activities of the filter to a
log file.

Task 2 Create Data Files


In this task, you create different data files in user-specific directories.

Complete the following steps:


1. Inside the /WEB-INF/data directory, create a directory with the
name of a user.
For example, you can name the directory jack.

Tool Reference Java Development: Other Files: Creating New Files


2.
3.
Create a my-library.txt data file in the directory you created.
Create another directory with the name of a different user.
m y
4. Create a my-library.txt data file in the new directory.
d e
You can split the original data file into two files.

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

Task 4 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 5 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the application by logging in as jack (or whatever user name

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

Exercise 2 (Advanced): Developing a Compression Filter

Note This is an advanced exercise. Only attempt this exercise if you


have completed Exercise 1: Developing a Login Filter on page Lab 9-2.
You are not required to complete this exercise.

In this exercise, you add a new filter to perform GZIP compression on the
output stream of the response.

This exercise consists of one task, Design a CompressionFilter Class.

Task Design a CompressionFilter Class


Your task is to design and then develop a CompressionFilter class.

Consider the following facts to help you design this filter:


The java.util.zip.GZIPOutputStream decorates a regular
java.io.OutputStream by compressing the bytes being written to
m y
the GZIP stream.

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

I n retrieve the servlet context.


In UNIX, you can easily monitor a log file using the tail

c l e
command:

Ora tail -f logfilename


This opens the file and displays lines as they are written to the log
file.

Using Filters in Web Applications 9-9


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise Summary

Exercise Summary

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Integrating Web Applications With Databases

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

Demonstration The demonstration for this lab can be found in the


1
2
3
demos/mod10_database directory.

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

Exercise 1: Starting the DVD Database


In this exercise, you launch the Java DB database management system
(DBMS) and populate the DVD library database schema and initial data.

This exercise consists of the following tasks:


Task 1 Creating the dvdlibrary Database
Task 2 Populating the dvdlibrary Database

Preparation
This exercise assumes that Application Server is installed and running.

Tool Reference Tool references used in this exercise:


Server Resources: Databases: Starting JavaDB


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

O ra 3. Connect to the newly created database using the


java:derby://localhost:1527/dvdlibrary connection.
Expand the Databases node in Services tab of the IDE.

10-2 Web Component Development With Servlet and JSP Technologies


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Starting the DVD Database

Right click the following database connection and select the Connect
menu option.

java:derby://localhost:1527/dvdlibrary [suned on SUNED]

Task 2 Populating the dvdlibrary Database


Complete the following steps:
1. Locate and examine the DVDLibrary.sql file.
The DVDLibrary.sql file is located (relative to the students home
directory) in the resources/lab10_database/db directory. Open
this file and confirm that it contains a list of SQL statements to create
ObjectIDs and Item tables for the dvdlibrary database and to
populate them with records.
2. Execute SQL commands to create and populate the tables of the
StockMarket database.
Use Runtime tab and expand the Databases node. Right click on the
node labelled, jdbc:derby://localhost:1527/dvdlibrary [suned on
SUNED] and select the Execute Command menu option. The
m y
selection of the Execute Command menu option opens an SQL
Command tab.
d e
Copy all the SQL commands shown in DVDLibrary.sql file you
c a
opened in the previous step and paste them into the SQL Command
tab.
e A
c l
Click the Run SQL button in the toolbar of the SQL Command tab to

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

Exercise 2: Integrating a Web Application With a Database


In this exercise, you update the application to use a new DVDLibrary class
that uses DVDLibraryDAO instead of reading from and writing to the file
system. Figure 10-1 shows the new architecture for the DVDLibrary web
application in which the service component (DVDLIbrary) uses a Data
Access Object (DAO) class to access the data store.

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

c l e Task 5 Test 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.

Tool Reference Tool references used in this exercise:


Java Development: Other Files: Deleting Files
Java Development: Java Classes: Copying Java Classes
Java EE Development: Web Modules: Web Deployment Descriptors:
Resource References
Java EE Development: Web Modules: Web Deployment Descriptors
Java EE Development: Configuring Java EE Resources: Configuring
Connection Pools
Java EE Development: Configuring Java EE Resources: Configuring
JDBC Resources
Java EE Development: Enterprise Application Projects: Building Java


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

5. Modify the line in the LoginFilter class that creates the


DVDLibrary object to use the username as the constructor
parameter.
6. Delete the data directory in the web directory of the project.

Task 2 Configure the Data Source in the Deployment


Descriptor
In this task, you add a resource reference to the deployment descriptor.
This resource reference specifies the DataSource used by the DAO. You
also remove unused items from the deployment descriptor and
application.

Complete the following steps:


1. Open the web.xml deployment descriptor.

Tool Reference Java EE Development: Web Modules: Web Deployment


Descriptors: Reference Configuration
2. Create a resource reference entry with the following properties:
m y
Resource Name: jdbc/dvdLibraryDB
d e
Resource Type: javax.sql.DataSource
c a
Authentication: Container

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

Complete the following steps:

Tool Reference Java EE Development: Configuring Java EE Resources:


Configuring Connection Pools
1. Create the JDBC Connection Pool with the following characteristics:
JDBC Connection Pool Name: dvdLibraryPool
Existing Connection:
jdbc:derby://localhost:1527/dvdlibrary
Resource Type: javax.sql.DataSource
Database Vendor: JavaDB
Properties:
ServerName: localhost
PortNumber: 1527
DatabaseName: dvdlibrary
User: suned
Password: suned

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

Task 4 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 5 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Add a new DVD item, and verify that the DAO saved the new DVD
item to 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
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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing JSP Pages

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.

Demonstration The demonstration for this lab can be found in the


1 demos/mod11_jsp directory.
2
3

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

Exercise 1: Converting the List Library View Component to


a JSP Page
In the following four exercises, you convert all of the view servlet
components into JSP pages. Figure 11-1 shows the current DVDLibrary
application architecture. All of the View components (List Library, Add
DVD Form, and Add DVD Success) are currently servlets.

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

Figure 11-2 shows the new DVDLibrary application architecture in which


all of the View servlets have been converted to JSP pages. This is the goal
of all four exercises in this module.

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

c l Figure 11-3 New DVDLibrary Logical Web Hierarchy

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.

This exercise consists of the following tasks:


Task 1 Convert the List Library Servlet
Task 2 Remove the Old Servlet Code
Task 3 Deploy the Web Application
Task 4 Test the Web Application

Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Creating JavaServer Pages


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:

c l e JSP File Name: list_library


Project: DVDLibrary

r a Location: Web Pages

O Options: JSP File (Standard Syntax)


Create a JSP Segment: not checked

11-4 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

2. Using the ListLibraryServlet servlet class as a guide, convert


the servlet code into JSP code.
You should use any scripting elements that you think are necessary
to do the conversion. Consider the following issues:
How do you import Java classes in a JSP page?
You do not need to set the content type or acquire the writer
stream, because the JSP environment does that for you.
You can strip off the out.print(<temple text>) code and
leave the raw <temple text> in the JSP page file.
Modify some of the template text so that you can verify that the
JSP page is being invoked.
3. Modify the index.html home page to change the link to the new
List Library JSP page.

Task 2 Remove the Old Servlet Code


In this task, you remove the old List Library servlet file and the
configuration information.
m y
Complete the following steps:
d e
1. Delete the ListLibraryServlet servlet class.
c a
2. Open the web.xml deployment descriptor and verify that the

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:

eBuild the DVDLibrary web application. Correct any errors you

I n encounter.

c l e 2. Deploy the DVDLibrary web application.

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

Task 4 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the List Library 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

Exercise 2: Converting the Add DVD Success View


Component to a JSP Page
This exercise consists of the following tasks:
Task 1 Convert the Success Servlet
Task 2 Remove the Old Servlet Code
Task 3 Modify the Struts Configuration File
Task 4 Deploy the Web Application
Task 5 Test the Web Application

Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Creating JavaServer Pages
m y
e

Java Development: Other Files: Deleting Files

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:

c l e JSP File Name: success


Project: DVDLibrary

ra Location: Web Pages

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

Options: JSP File (Standard Syntax)


Create a JSP Segment: not checked
2. Using the SuccessServlet servlet class as a guide, convert the
servlet code into JSP code. Use only JSP Standard Actions to do the
conversion.

Task 2 Remove the Old Servlet Code


In this task, you remove the old Success servlet and the configuration
information.

Complete the following steps:


1. Delete the SuccessServlet class.
2. Open the web.xml deployment descriptor and verify that the
definition and mapping for the SuccessServlet servlet are
removed.

Task 3 Modify the Struts Configuration File


m y
d e
In this task, you modify the action forward path for the Success view.

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

Task 5 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the Success page of the Add DVD use case.

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

Exercise 3: Refactoring the Success JSP Page to Use EL


In this exercise, you refactor the Success JSP page to use the Expression
Language (EL) syntax.

This exercise consists of the following tasks:


Task 1 Refactor the Success JSP Page
Task 2 Deploy the Web Application
Task 3 Test the Web Application

Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.

Tool references used in this exercise:


Java EE Development: Enterprise Application Projects: Building Java
EE Applications
m y
Java EE Development: Enterprise Application Projects: Deploying
d e
Java EE Applications

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

Task 2 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 3 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the Success page of the Add DVD use case.

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

Exercise 4: Converting the Add DVD Form Component to a


JSP Page
This exercise consists of the following tasks:
Task 1 Convert the AddDVDFormServlet Servlet
Task 2 Remove the Old Servlet Code
Task 3 Modify the Struts Configuration File
Task 4 Deploy the Web Application
Task 5 Test the Web Application

Preparation
This exercise assumes that the application server and the Derby database
server are installed and running.

Tool Reference Tool references used in this exercise:


Java EE Development: Web Modules: Creating JavaServer Pages
m y
e

Java Development: Other Files: Deleting Files

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:

c l e JSP File Name: add_dvd


Project: DVDLibrary

O ra Location: Web Pages

11-12 Web Component Development With Servlet and JSP Technologies


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

Options: JSP File (Standard Syntax)


Create a JSP Segment: not checked
2. Using the AddDVDFormServlet servlet class as a guide, convert the
servlet code into JSP code.
You should use any JSP technology that you think is necessary to do
the conversion.
3. Modify the index.html home page to change the link to the new
Add DVD form JSP page.

Task 2 Remove the Old Servlet Code


In this task, you remove the old Add DVD form servlet file and the
configuration information.

Complete the following steps:


1. Delete the AddDVDFormServlet class.
2. Open the web.xml deployment descriptor and verify that the
definition and mapping for the AddDVDFormServlet servlet are
m y
removed.

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.

c l e Complete the following steps:

ra 1. Build the DVDLibrary web application. Correct any errors you

O encounter.

Developing JSP Pages 11-13


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

2. Deploy the DVDLibrary web application.

Task 5 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the Add DVD form page. Test the error handling and
repopulating features to make sure these features still work.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing JSP Pages Using Custom Tags

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.

Demonstration The demonstration for this lab can be found in the


1 demos/mod12_jsp_tags directory.
2
3

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

Exercise 1: Refactoring the List Library JSP Page Using


the JSTL Custom Tags
In this exercise, you refactor the List Library JSP page to eliminate the
scripting code by using the JSTL custom tag library.

This exercise consists of the following tasks:


Task 1 Refactor the List Library JSP Page
Task 2 Deploy the Web Application
Task 3 Test the Web Application

Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.

Tool Reference Tool references used in this exercise:

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.

c l e 3. Add a taglib directive to include the JSTL functions library. This


library uses the URI of

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.

12-2 Web Component Development With Servlet and JSP Technologies


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

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.

Task 2 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
m y
encounter.

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

Exercise 2: Refactoring the Add DVD Form JSP Page


Using the JSTL Custom Tags
In this exercise, you refactor the Add DVD form JSP page to eliminate the
scripting code by using the JSTL custom tag library.

This exercise consists of the following tasks:


Task 1 Refactor the add_dvd.jsp Page
Task 2 Deploy the Web Application
Task 3 Test the Web Application

Preparation
This exercise assumes that the application server and the Java DB
database server are installed and running.

Tool Reference Tool references used in this exercise:

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

3. Refactor the error reporting code:


a. Use the JSTL if tag to test whether the errorMsgs list is null or
empty.
The built-in EL operator empty performs this check. For
example, ${empty errorMsgs} is true if and only if (a) the
errorMsgs attribute does not exist or (b) if it does exist, then
there are no elements in the list.
b. Use the JSTL forEach tag to iterate over the list of errors.
4. Refactor the drop-down list repopulating code using a combination
of the forEach and if tags.

Task 2 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
m y
2. Deploy the DVDLibrary web application.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing Web Applications Using Struts Action


Forms

Objectives
Upon completion of this lab, you should be able to develop ActionForm
components for a flexible Struts application.

Demonstration The demonstration for this lab can be found in the


1 demos/mod13_struts2 directory.

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

Exercise 1: Developing a Struts Action Form


In this exercise, you simplify the Add DVD boundary components by
adding an action form that works in conjunction with the Add DVD
controller and Add DVD form JSP page. Figure 13-1 shows the three
physical components that now make up the Add DVD boundary
component.

AddDVD

add_dvd.jsp
<% AddDVDForm AddDVDAction

%>

Figure 13-1 The AddDVD Boundary Components


m y
Figure 13-2 shows a UML class diagram for the AddDVDForm component.
d e
Use this diagram as a guide for creating the AddDVDForm class.

c a
e
AddDVDForm
A
l
-title : String = null
-year : String = null

a c
-genre : String = null
-newGenre : String = null

The mutator methods are


used by Struts to populate the
r
+setTitle(title:String)

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

This exercise consists of the following tasks:


Task 1 Copy the Error Messages Properties File
Task 2 Create the AddDVDForm Bean
Task 3 Modify the Add DVD Controller
Task 4 Modify the Struts Configuration File
Task 5 Modify the Add DVD Form
Task 6 Deploy the Web Application
Task 7 Test the Web Application

Preparation
This exercise assumes that Application Server and the Derby database
server are installed and running.

Tool Reference Tool references used in this exercise:


Java Development: Copying Existing Resources

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:

c l e 1. Delete the web-app.properties file in the com.dvd.web source

ra package of the DVDLibrary project.

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

2. Copy the web-app.properties file in the


resources/mod12_struts2 directory to the com.dvd.web source
package of the DVDLibrary project.
You add error messages to this file in Task 2 Create the
AddDVDForm Bean on page Lab 13-4.

Task 2 Create the AddDVDForm Bean


In this task, you add an action form to the application.

Tool Reference Java EE Development: Web Modules: Struts ActionForm


Beans

Complete the following steps:


1. Create a new Struts ActionForm Bean with the following
characteristics:
Name: AddDVDForm
Project: DVDLibrary
m y
Package: com.dvd.view

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

c l e b. Create get and set methods for each instance variables.

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.

Task 3 Modify the Add DVD Controller


In this task, you modify the AddDVDAction controller to use the new
AddDVDForm.

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

Task 4 Modify the Struts Configuration File


In this task, you modify the Struts configuration file to define the form
bean created in Task 2 Create the AddDVDForm Bean.

Complete the following steps:


1. Open the struts-config.xml file.
2. Verify the declaration of the form bean (created in Task 2 Create
the AddDVDForm Bean).
3. Modify the AddDVD action declaration and add the attributes
supplied in the Table 13-1.

Table 13-1 The AddDVD Action Attributes

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

Task 6 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 7 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the application.
3. Try to add a new DVD and see what happens when you make errors
in the 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
Developing Web Applications Using Struts Action Forms 13-7
Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2 (Advanced): Using the Struts HTML Tag Library

Exercise 2 (Advanced): Using the Struts HTML Tag Library

Note This is an advanced exercise. Only attempt this exercise if you


have completed Exercise 1: Developing a Struts Action Form on
page Lab 13-2. You are not required to complete this exercise.

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.

Task Refactor the AddDVDForm JSP Page


Complete the following steps:
1. Research the Struts HTML tag library in the online Struts
documentation.
2. Use the HTML form custom tags in the Add DVD form 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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Building Reusable Web Presentation Components

Objectives
Upon completion of this lab, you should be able to construct a JSP page
with a complex layout, using existing JSP page segments.

Demonstration The demonstration for this lab can be found in the


1 demos/mod14_jsp_reuse directory.
2
3

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

Exercise: Building a JSP Page From JSP Fragments


In this exercise, you are given a prototype layout for the DVDLibrary
application, as shown in Figure 14-1.

Banner
Logo

Body
Side-bar
menu
Copyright
notice

Figure 14-1 Dukes Arcade Web Application Layout


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-2 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

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

O Java EE Development: Web Modules: JavaServer Pages

Building Reusable Web Presentation Components 14-3


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise: Building a JSP Page From JSP Fragments

Java EE Development: Web Modules: Web Deployment Descriptors:


Page Configuration
Java EE Development: Enterprise Application Projects: Building Java
EE Applications
Java EE Development: Enterprise Application Projects: Deploying
Java EE Applications

Task 1 Copy Resources to the Application


In this task, you copy resources to the directory structure illustrated in
Figure 14-2 on page Lab 14-3.

Complete the following steps:


1. Copy the images directory from the resources/jsp_reuse
directory to the web directory.
2. Create the view/layout subdirectory (illustrated in Figure 14-2 on
page Lab 14-3) under the WEB-INF directory.
3. Copy the mainLayout.jsp layout page from the
resources/jsp_reuse directory to the new WEB-
m y
INF/view/layout directory.

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.

Task 3 Create the Tiles Pages for Each View


In this task, you create Tiles pages for each view in the application. These
pages are located in the web directory.

Complete the following steps:


1. Open the index.jsp page.
2. Add a tag directive to the page, using
http://struts.apache.org/tags-tiles as the URI and
tiles as the prefix.
m y
3. Modify the index.jsp file in the web directory.
d e
a. Insert the path to the layout page.
c a
b. Insert a name for the page in the subTitle attribute.

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

Task 4 Deploy the Web Application


In this task, you build and deploy the DVDLibrary web application.

Complete the following steps:


1. Build the DVDLibrary web application. Correct any errors you
encounter.
2. Deploy the DVDLibrary web application.

Task 5 Test the Web Application


In this task, you test the web application using a web browser.

Complete the following steps:


1. Refresh the DVDLibrary web application home page.
2. Test the application. Access all of the views in the application to
make sure that the layout has been applied throughout.

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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

Developing a Basic JavaServer Faces


Application

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

Exercise 1: Creating a JavaServer Faces Hello World


Application
In this exercise, you create an application with the basic components of a
JavaServer Faces web application.

Preparation
You must have the following installed on your system:
NetBeans software
GlassFish Application Server
A web browser

Completed solutions for all the labs can be found in:


/export/home/student/solutions/labG_jsf
Implement the List Library feature

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

Tool Reference Java EE Development: Web Modules: Creating Web


Application Projects
2. Create a Java class file for the JavaServer Faces backing bean. For this
first exercise, the backing bean has only two properties:
private String username;
private String password;
Each property has getter and setter methods:
public String getUsername()
public void setUsername(String newValue)
public String getPassword()
public void setPassword(String newValue)
a. Add a new Java Class file.
Class Name: DVDLibraryBean
Project: DVDLibrary
Location: Source Packages
Package: com.example.model
m y
d e
Tool Reference Java Development: Java Classes: Creating Java Classes
b.
c
Add the declaration of the username and password properties a
as shown above.

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.

Developing a Basic JavaServer Faces Application A-3


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Creating a JavaServer Faces Hello World Application

a. Open the JavaServer Faces application configuration file,


faces-config.xml, for editing.
The faces-config.xml file is found in the Web Pages/WEB-
INF under the NetBeans Projects tab.1
b. Register the new backing bean by adding the following XML to
the faces-config.xml file.2
<managed-bean>
<managed-bean-name>
dvd
</managed-bean-name>
<managed-bean-class>
com.example.model.DVDLibraryBean
</managed-bean-class>
<managed-bean-scope>
session
</managed-bean-scope>
</managed-bean>
c. Save and close 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.

A-4 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

Tool Reference Java EE Development: Web Modules: JavaServer Pages


4. Create a login page to authenticate the user. This page is a simple
form with a user name and password field. You use it to log in to the
DVDLibrary web application.

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).

a. Add a new JSP page file.


Project: DVDLibrary
Category: Web
File Type: JSP
JSP File Name: login (login.jsp)
Project: DVDLibrary

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.

c l e b. Copy the contents of the partially completed index.jsp source


file:

Ora /export/home/student/resources/labA_jsf/exercise1/index.jsp
into the file you created in the previous step.

Developing a Basic JavaServer Faces Application A-5


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 1: Creating a JavaServer Faces Hello World Application

c. Replace the first and second TODO comments with the


appropriate taglib prefix. (Refer to the login.jsp page for a
hint on what it should be.)
d. Replace the third TODO comment. Replace the TODO comments
with the name of the appropriate properties from the
DVDLibraryBean.
6. Change the web applications welcome file to faces/login.jsp,
instead of index.jsp.
a. Open the web application configuration file, web.xml, for
editing.
The web.xml file is found under the Web Pages/WEB-INF node
under the NetBeans Projects tab.
b. Change the value of the <welcome-file-list> element to be
faces/login.jsp.

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>

A-6 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

/index.jsp
</to-view-id>
</navigation-case>
</navigation-rule>
8. Test the application as it exists to this point.

Figure A-1 Welcome Screen

Tool Reference Java Application Projects: Running Projects Classes

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

Exercise 2: Creating Application Messages


In this exercise, you modify the application so that the static text
displayed in the web pages comes from a Java technology properties file.
Moving static text out of the web pages into a properties file makes the
application text consistent, and it makes the design more flexible. For
example, you can use the properties files to easily internationalize your
applications messages.

Note Static text strings in JavaServer Faces applications are called


messages.

This exercise consists of the following tasks:


Task 1 Modify the Application to Use Messages
Task 2 Modify the Welcome Message

Task 1 Modify the Application to Use Messages


m y
Complete the following steps.
d e
1. Create a new file, messages.properties. The properties file must
be located somewhere in the Java programming language classpath.
c a
A typical place is in the source default package within the

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

A-8 Web Component Development With Servlet and JSP Technologies


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 2: Creating Application Messages

File Name: messages (messages.properties)


Project: DVDLibrary
Folder: src\java

Tool Reference Java Classes: Modifying Java Classes: Adding Properties


b. Copy the contents of the partially completed
messages.properties source file
/export/home/student/resources/labA_jsf/exercise2/message.properties
into the file you created in the previous step.
2. Add the following line in the <head> section of each JSP page file to
associate msg with the messages.properties file.
<f:loadBundle basename="messages" var="msg"/>

Note The messages base name implies the messages.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

Exercise 3: Localizing Application Messages


This exercise consists of one task, Modify the Application to Use
Messages.

Task 1 Modify the Application to Use Messages


Complete the following steps:
1. Determine the ISO-369 language code for the language the you want
to support. For example, use de for German.

Note Language and country codes can be found at:


http://java.sun.com/j2se/1.5.0/docs/api/java/util/Locale.html

2. In the same file directory as messages.properties, create a file


named messages_de.properties for messages in German. The
names of the internationalized message files must use the following
form:
m y
messages_<language code>.properties

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

A-10 Web Component Development With Servlet and JSP Technologies


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 3: Localizing Application Messages

Project Type: Properties File


File Name: messages_de (messages_de.properties)
Project: DVDLibrary
Folder: src\java
b. Copy the contents of the partially completed
messages_de.properties source file,
/export/home/student/resources/labA_jsf/exercise3/messages_de.properties
3. Create a new backing bean to implement the logic to enable
localization responses for this view.
a. Create a new Java technology class file using the following
specifications:
Class Name: LocaleBean
Project: DVDLibrary
Location: Source Packages
Package: com.example.view
b. Copy the contents of the partially completed LocaleBean.jsp
source file,
m y
/export/home/student/resources/labA_jsf/exercise3/LocaleBean.java
d e
c.
into the file you created in the previous step.
Find the TODO command and complete the setEn method using
c a
the setDe method as an example.

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.

l & On The NetBeans software inserts the appropriate import

n a e statements near the beginning of the file.


4.

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

b. Register the new class by adding the following XML to the


faces-config.xml file.

<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)

Exercise 4: Localizing Application Messages (Optional)


This exercise consists of one task.

Task 1 Using Cascading Style Sheets (CSS) to Move


the Locale Links

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.

Complete the following steps:


1. Enclose both command links in an HTML division with a class
attribute.
<DIV id=langChoice CLASS="localeLinks">
... <h:commandLink ...
... <h:commandLink ...
</DIV>
m y
d e
Note Place the CSS file in the same directory as the other web files.
c a
2. Use a CSS file to apply a style that re-positions the division.
e A
c l
.localeLinks { position: absolute; top: 0; left: 40%; width: 60%; height: 4em; }
3.
r a
Add an HTML link tag in the head of the page, to provide access to

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.

c l JavaServer Faces rewrites the ID attributes to prevent duplicating ID

r a attribute names among all of its embedded components. Applying styles


based on a class attribute is much safer.

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

Exercise 5: Creating a Layout Navigation for the


Application
This exercise consists of one task, Set Up Application Navagation.

Review Figure A-2, which is a navigational design diagram.

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

c l e goToAdd_dvd=Add a DVD to my collection


goToSet_prefs=Set user preferences

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

5. Add h:commandLinks or an equivalent action components to the


home page (index.jsp).
...
<h:form>
<p>
<h:commandLink action="list">
<h:outputText value="#{msg.goToList_library}"/>
</h:commandLink>
<p>
<h:commandLink action="add">
<h:outputText value="#{msg.goToAdd_dvd}"/>
</h:commandLink>
<p>
<h:commandLink action="prefs">
<h:outputText value="#{msg.goToSet_prefs}"/>
</h:commandLink>
</h:form>
...
6. Test the application by running it, logging in, and then clicking each
link on the index.jsp page to see that the navigation works as you
expected.

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

Exercise 6: Implementing the List Library Feature


In this exercise, you implement a DataTable component to display a list
of the DVDs from a users library in the list_library page.

This exercise has one task, List the Database User Data.

Task List the Database User Data


Complete the following steps:
1. Add the provided DVDItem.java and DVDLibraryDAO.java class
definition file to the com.example.model source package,
/export/home/student/resources/labA_jsf/exercise6
Program files: DVDItem.java and DVDLibraryDAO.java

Note These classes are not registered in faces-config.xml because


they are not backing beans; they do not interface directly with any
JavaServer Faces components.
m y
d e
2. Modify the DVDLibraryBean to use the new DAO.
a. Add the following import statements:
c a
import java.util.List;

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.

n a eAdd a getter method, getDVDCollection that returns a

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}

Developing a Basic JavaServer Faces Application A-17


Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1
Exercise 6: Implementing the List Library Feature

d. Add a method, getSize, which returns the number of items in


the dvdCollection.
public int getSize() {
return getDVDCollection.size();
}

e. Modify the setUsername.


public void setUsername(String username){
this.username = username;
this.dvdCollection = null;
}
3. At the top of the list_library.jsp page, add a greeting to
announce how many DVDs are in the collection.
<h:outputFormat value="#{msg.welcome_list}">
<f:param value="#{dvd.size}"/>
</h:outputFormat>
4. Add a DataTable component to the list_library.jsp file.
a. The form should retrieve DVDItem values from the model using
the getDVDCollection method you created in the previous
exercise.
m y
b. The form should have a column for each of the fields in the
d e
c.
DVDItem returned from the model: title, year, and genre.
Use facet components to place a header at the top of each c a
column.

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>

A-18 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

<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

Discussion Take a few minutes to discuss what experiences, issues, or


discoveries you had during the lab exercise.
!
?
Experiences
Interpretations
Conclusions
Applications

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

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