You are on page 1of 412

IBM Rational University

Mastering Servlet and JSP Development with


Rational Application Developer V7
RD792 / DEV450 July 2007
Instructor Manual Volume 3
Part No. 800-027344-000









IBM Corporation
Rational University
Mastering Servlet and JSP Development with Rational Application Developer V7
Instructor Manual Volume 3
July 2007
Copyright International Business Machines Corporation, 2007. All rights reserved.
This document may not be reproduced in whole or in part without the prior written permission
of IBM.
The contents of this manual and the associated software are the property of IBM and/or its
licensors, and are protected by United States copyright laws, patent laws, and various
international treaties. For additional copies of this manual or software, please contact Rational
Software.
IBM and the IBM logo are trademarks or registered trademarks of IBM Corporation, in the
United States, other countries or both.
Rational, the Rational logo, ClearCase, ClearCase LT, ClearCase MultiSite, Unified Change
Management, Rational SoDA, and Rational XDE are trademarks or registered trademarks of
International Business Machines Corporation in the United States, other countries or both.
WebSphere, the WebSphere logo, and Studio Application Developer, are trademarks or
registered trademarks of International Business Machines Corporation in the United States, other
countries or both.
Microsoft Windows 2000, Microsoft Word, and Internet Explorer, among others, are trademarks
or registered trademarks of Microsoft Corporation.
Java and all Java-based marks, among others, are trademarks or registered trademarks of Sun
Microsystems in the United States, other countries or both.
UNIX is a registered trademark of The Open Group in the United States, other countries or
both.
Other company, product and service names may be trademarks or service marks of others.
Printed in the United States of America.
This manual prepared by:
IBM Rational Software
555 Bailey Ave. Santa
Teresa Lab San Jose CA
95141-1003 USA
Mastering Servlet & JSP Dev. With IBM RAD V7 Table of Contents
Contents
Unit 22: JSP Custom Tags
JSP Custom Tags ................................................................................................... 22-1
Unit objectives....................................................................................................... 22-2
JSP custom tags overview ..................................................................................... 22-4
Why use JSP custom tags? .................................................................................... 22-6
Steps to create and use a custom tag library .......................................................... 22-8
Tag usage example .............................................................................................. 22-10
JSP page without custom tags.............................................................................. 22-12
Using custom tags with Application Developer .................................................. 22-14
JSP Standard Tag Library (JSTL)........................................................................ 22-16
Sample JSTL tags ................................................................................................ 22-18
forEach tag........................................................................................................... 22-20
Anatomy of a tag ................................................................................................. 22-22
Tag examples....................................................................................................... 22-24
Describing tags to the JSP container ................................................................... 22-26
General format of the TLD (1 of 2) ..................................................................... 22-28
General format of the TLD (2 of 2) ..................................................................... 22-30
Location of TLD file............................................................................................ 22-32
JSP taglib directive .............................................................................................. 22-34
Tag handler base classes...................................................................................... 22-36
Example tag ......................................................................................................... 22-38
Processing tags with attributes: How it works..................................................... 22-40
What needs to be done?....................................................................................... 22-42
The TransformTag class ...................................................................................... 22-44
The doTag() method ............................................................................................ 22-46
The taglib descriptor ............................................................................................ 22-48
Using the <transform> tag................................................................................... 22-50
Packaging ............................................................................................................ 22-52
Checkpoint........................................................................................................... 22-54
Checkpoint solutions ........................................................................................... 22-56
Unit summary ...................................................................................................... 22-58
Unit 23: JSP Tag Files
JSP Tag Files ......................................................................................................... 23-1
Unit objectives....................................................................................................... 23-2
Overview of tag files ............................................................................................. 23-4
Calling a tag file from a JSP.................................................................................. 23-6
Body content from caller JSP ................................................................................ 23-8
Parameters from caller JSP.................................................................................. 23-10
Fragments from caller JSP................................................................................... 23-12
Tag directive in tag file........................................................................................ 23-14
Attribute directive in tag file................................................................................ 23-16
Variable directive in tag file ................................................................................ 23-18
Implicit objects available in a tag file.................................................................. 23-20
Example of calling a tag file................................................................................ 23-22
Tag wile with body content and a fragment ........................................................ 23-24
Tag file with packaging ....................................................................................... 23-26
Copyright IBM Corp. 2003, 2007 i
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Mastering Servlet & JSP Dev. With IBM RAD V7 Table of Contents
Checkpoint........................................................................................................... 23-28
Checkpoint solutions ........................................................................................... 23-30
Unit summary ...................................................................................................... 23-32
Unit 24: Servlet Filtering
Servlet Filtering ..................................................................................................... 24-1
Unit objectives....................................................................................................... 24-2
Introducing filters .................................................................................................. 24-4
Typical uses of filters............................................................................................. 24-6
Filter processing flow............................................................................................ 24-8
Filter chain processing......................................................................................... 24-10
doFilter() nested calls .......................................................................................... 24-12
Typical doFilter() pattern..................................................................................... 24-14
Implementing a filter ........................................................................................... 24-16
Application Developer filter support ................................................................... 24-18
Creating a new filter in Application Developer................................................... 24-20
The javax.servlet.Filter interface ......................................................................... 24-22
The javax.servlet.FilterConfig interface .............................................................. 24-24
The javax.servlet.FilterChain interface................................................................ 24-26
Describing the filter ............................................................................................. 24-28
Example of a filter description ............................................................................ 24-30
Describing the filter mapping .............................................................................. 24-32
Examples of filter mapping ................................................................................. 24-34
Configuring filters with Application Developer.................................................. 24-36
Configuring filter chaining .................................................................................. 24-38
Example of configuring filter chaining................................................................ 24-40
Configuring filters for reuse ................................................................................ 24-42
Example of configuring filter reuse..................................................................... 24-44
Filters with RequestDispatcher............................................................................ 24-46
Dispatcher element .............................................................................................. 24-48
Filter code examples ............................................................................................ 24-50
Logger filter: Function description...................................................................... 24-52
Logger filter: Deployment Descriptor ................................................................. 24-54
Logger filter: init() and destroy() methods .......................................................... 24-56
Logger filter: doFilter() method........................................................................... 24-58
Logger filter: How it works ................................................................................. 24-60
FormChecker filter: Function description............................................................ 24-62
FormChecker filter: Deployment descriptor........................................................ 24-64
FormChecker filter: init() and destroy() methods................................................ 24-66
FormChecker filter: doFilter() method (1 of 2) ................................................... 24-68
FormChecker filter: doFilter() method (2 of 2) ................................................... 24-70
FormChecker filter: How it works....................................................................... 24-72
Wrapping request and response objects................................................................ 24-74
Trailer filter: Function description....................................................................... 24-76
Trailer filter: Deployment descriptor ................................................................... 24-78
Trailer filter: init() method................................................................................... 24-80
Trailer filter: doFilter() method ........................................................................... 24-82
Custom response: StringResponse....................................................................... 24-84
Trailer filter: How it works.................................................................................. 24-86
Checkpoint........................................................................................................... 24-88
Copyright IBM Corp. 2003, 2007 ii
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Mastering Servlet & JSP Dev. With IBM RAD V7 Table of Contents
Checkpoint solutions ........................................................................................... 24-90
Unit summary ...................................................................................................... 24-92
Unit 25: Servlet Listeners
Servlet Listeners .................................................................................................... 25-1
Unit objectives....................................................................................................... 25-2
Basic concepts of Servlet Event Listeners............................................................. 25-4
Examples of Servlet Listener use........................................................................... 25-6
How to create a Servlet Listener............................................................................ 25-8
Selecting Servlet Listener interfaces.................................................................... 25-10
Selecting methods for ServletContext events ...................................................... 25-12
Selecting methods for HttpSession events........................................................... 25-14
Selecting methods for ServletRequest events...................................................... 25-16
Defining Listeneres to the Web application ........................................................ 25-18
Sample Servlet Listener application (1 of 2) ....................................................... 25-20
Sample Servlet Listener application (2 of 2) ....................................................... 25-23
Creating new Servlet Listeners with wizards (1 of 2) ......................................... 25-25
Creating new Servlet Listeners with wizards (2 of 2) ......................................... 25-27
Maintaining the Listener Definition .................................................................... 25-29
Checkpoint........................................................................................................... 25-31
Checkpoint solutions ........................................................................................... 25-33
Unit summary ...................................................................................................... 25-35
Unit 26: Best Practices for Server-Side Application Dev
Best Practices for Server-Side Application Dev.................................................... 26-1
Unit objectives....................................................................................................... 26-2
The layering concept ............................................................................................. 26-4
Advantages of layering.......................................................................................... 26-7
Disadvantages of layering...................................................................................... 26-9
Two-layer architecture......................................................................................... 26-11
Problems with two-layer architecture.................................................................. 26-13
Three-layer architecture....................................................................................... 26-15
Layering in J2EE................................................................................................. 26-18
Sample implementation of patterns (1 of 2)......................................................... 26-20
Sample implementation of patterns (2 of 2)......................................................... 26-22
Sample Layered application................................................................................. 26-24
Presentation Layer (client)................................................................................... 26-26
Presentation Layer (servlet)................................................................................. 26-28
Presentation Layer (controller) ............................................................................ 26-30
Presentation Layer (state machine)...................................................................... 26-32
Business Layer (Action Processors) .................................................................... 26-34
Business Layer (data transfer objects) ................................................................. 26-36
Business Layer (session faades)......................................................................... 26-38
Business Layer (model helpers)........................................................................... 26-41
Data Layer (mappers) .......................................................................................... 26-43
Data Layer (entity EJBs) ..................................................................................... 26-45
Decoupling the layers .......................................................................................... 26-47
Accessing the data layer directly ......................................................................... 26-49
Physical layering.................................................................................................. 26-51
Servlet considerations.......................................................................................... 26-54
Copyright IBM Corp. 2003, 2007 iii
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Mastering Servlet & JSP Dev. With IBM RAD V7 Table of Contents
JSP design considerations.................................................................................... 26-56
Other JSP guidelines............................................................................................. 26-58
Synchronizer token: Problem .............................................................................. 26-60
Synchronizer token: Solution (1 of 2) ................................................................. 26-62
Synchronizer token: Solution (2 of 2) ................................................................. 26-64
Checkpoint........................................................................................................... 26-66
Checkpoint solutions ........................................................................................... 26-68
Unit summary ...................................................................................................... 26-70
Unit 27: J2EE Packaging and Deployment
J2EE Packaging and Deployment.......................................................................... 27-1
Unit objectives ....................................................................................................... 27-2
J2EE packaging ..................................................................................................... 27-4
J2EE packaging Containment hierarchy............................................................. 27-6
EJB module............................................................................................................ 27-8
Web module......................................................................................................... 27-10
Application client module.................................................................................... 27-12
Resource adapter module..................................................................................... 27-14
Enterprise application.......................................................................................... 27-16
Checkpoint........................................................................................................... 27-18
Checkpoint solutions ........................................................................................... 27-20
Unit summary ...................................................................................................... 27-22
Unit 28: Installing an Application in WebSphere Application
Server V6.1
Installing an Application in WebSphere Application Server V6.1........................ 28-1
Unit objectives ....................................................................................................... 28-2
WebSphere Administration Console ..................................................................... 28-4
Administrative Console overview ......................................................................... 28-6
Administrative Console navigation tree ................................................................ 28-8
Applications: Console options............................................................................. 28-10
Applications: Installation (1 of 2)........................................................................ 28-13
Applications: Installation (2 of 2)........................................................................ 28-15
Applications: Modification.................................................................................. 28-17
Servers: Configuration (1 of 2)............................................................................ 28-19
Servers: Configuration (2 of 2)............................................................................ 28-21
Resources: Configuration .................................................................................... 28-23
Resources: JDBC DataSources............................................................................ 28-25
Resources: JMS connections ............................................................................... 28-27
Saving master configuration................................................................................ 28-29
Checkpoint........................................................................................................... 28-31
Checkpoint solutions ........................................................................................... 28-33
Unit summary ...................................................................................................... 28-35
Unit 29: Web Application Security
Web Application Security...................................................................................... 29-1
Unit objectives....................................................................................................... 29-2
Role-based security................................................................................................ 29-4
Define security roles for Web applications............................................................ 29-6
Copyright IBM Corp. 2003, 2007 iv
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Mastering Servlet & JSP Dev. With IBM RAD V7 Table of Contents
Constrain access based on security role................................................................. 29-8
Gather roles in the enterprise application ............................................................ 29-10
Web container client authentication .................................................................... 29-12
Configure client authentication method............................................................... 29-14
Declarative and programmatic security ............................................................... 29-16
Define security role references ............................................................................ 29-18
Enterprise application security overview............................................................. 29-20
WebSphere environment security layers ............................................................. 29-22
Security in WebSphere (1 of 2) ........................................................................... 29-24
Security in WebSphere (2 of 2) ........................................................................... 29-26
Manager security in WebSphere.......................................................................... 29-28
Checkpoint........................................................................................................... 29-30
Checkpoint solutions ........................................................................................... 29-32
Unit summary ...................................................................................................... 29-34
Unit 30: Course Summary
Course Summary ................................................................................................... 30-1
What this course was about ................................................................................... 30-2
Resources............................................................................................................... 30-4
Other WebSphere courses ..................................................................................... 30-6
Finally.................................................................................................................... 30-8
Copyright IBM Corp. 2003, 2007 v
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
xviii Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-1
V4.0
Uempty
Unit 22.JSP Custom Tags
Estimated time
00:45
What this unit is about
This unit describes the development and use of JSP custom tags.
What you should be able to do
After completing this unit, you should be able to:
Describe the advantages of JSP custom tags
List the major steps in developing and using JSP custom tags
Describe the basic processing flow for JSP custom tags
Develop basic tag handler classes to implement JSP custom tags
Create and modify taglib descriptor files
Package tag handler classes into taglibs using Application
Developer
How you will check your progress
Accountability:
Checkpoint
Lab Exercises
References
http://www.ibm.com/developerworks/java/library/j-jstl0211.html
A JSTL primer, Part 1: The expression language
http://www.ibm.com/developerworks/java/library/j-jstl0318/
A JSTL primer, Part 2: Getting down to the core
http://www.ibm.com/developerworks/java/library/j-jstl0415/
A JSTL primer, Part 3: Presentation is everything
http://www.ibm.com/developerworks/java/library/j-jstl0520/
A JSTL primer, Part 4: Accessing SQL and XML
content
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Describe the advantages of using JSP custom tags
List the major steps in developing and using JSP custom tags
Develop basic tag handler classes to implement JSP custom
tags
Create and modify taglib descriptor files
Package JSP taglib implementation classes and taglib
descriptor files
Understand the uses of the JSTL
Name some of the tags included in the JSTL and their
purposes
After completing this unit, you should be able to:
Describe the advantages of using JSP custom tags
List the major steps in developing and using JSP custom tags
Develop basic tag handler classes to implement JSP custom
tags
Create and modify taglib descriptor files
Package JSP taglib implementation classes and taglib
descriptor files
Understand the uses of the JSTL
Name some of the tags included in the JSTL and their
purposes
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-3
V4.0
Uempty
Instructor notes:
Purpose This unit introduces the basic concepts of JSP custom tags. After completion
of this unit, the learner should be able to write a simple tag in IBM Rational Application
Developer.
Details After introducing reasons for using JSP tags and basic concepts such as
structure of a tag, steps for developing tags, and using the tags in JSP, the unit covers the
tag library descriptor (TLD) and classes used to implement tags. The remainder of the unit
consists of two examples that show iterative development of a date formatting tag. Each
example covers the function of the tag, how it works (processing flow), the TLD used to
describe the tag, tag handler code sample and explanation, and how it is used.
Additional information This unit is a prerequisite for Exercise 9.
Transition statement Next: JSP Custom Tags Overview
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-2. JSP custom tags overview RD7927.0
Notes:
You may sometimes see a JSP tag referred to as an action and vice-versa. More precisely,
an action is the function performed by a specific tag.
The first group of standard stags mentioned above has to do with bean access from JSP
pages. The second group has to do with interaction between JSP pages and other Web
resources. Both of these groups have already been discussed.
The last group of tags have to do with plugins. The <plugin> tag generates HTML
elements that result in download of a Java plug-in to the browser and execution of a
specified applet or JavaBean. The <fallback> tag specifies text to include if the browser is
unable to support the HTML elements generated by <plugin>. The <params> and
<param> tags specify parameters for the plugin.
3
JSP custom tags overview
Nine standard actions must be provided by any compliant JSP
implementation:
useBean, setProperty, getProperty
include, forward
plug-in, params, param, fallback
Custom tags allow developers to create additional actions
beyond the standard set
Custom actions are invoked using custom tags in a JSP page
Tag libraries are collections of custom tags
Support for JSP custom tags is required by the JSP
specification
<jsp:useBean id="customer" class="com.ibm.model.customer" />
<jsp:setProperty name="customer" property="id" value="0" />
<jsp:include page=banner.jsp />
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-5
V4.0
Uempty
Instructor notes:
Purpose Provide overview of use of custom tags in JSP pages.
Details
Additional information
Transition statement Next: Why Use JSP Custom Tags?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-3. Why use JSP custom tags? RD7927.0
Notes:
Enterprise Web applications are large and complex and required a diverse set of skills to
develop. Role-based development is based on the premise that particular parts of the
application should be developed by specialists with the most appropriate skills and tools to
bring to the particular area. Using JSP custom tags contributes to the role-based
development model.
JSPs are primarily to be used for presentation and are the domain of the Web designer and
developer, not the Java developer. JSP custom tags provide a way for the Web designer to
implement logic to produce complex presentations without the need to become involved in
the details of Java.
The use of custom JSP tags for presentation logic is a best practice because it allows the
right tools to be used for the right jobs within the model-view-controller design pattern.
4
Why use JSP custom tags?
Role-based development
Model classes (business objects and data storage layers)
are developed by Java and EJB developers
Controller classes (servlets) are developed by Java
developers
View-based JSP pages are developed by HTML developers
Different roles:
Use different tools
Have different skills
Best practice
MVC design is well established
Use the right tools for the right jobs
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-7
V4.0
Uempty
Instructor notes:
Purpose Stimulate student interest in tags.
Details
Additional information
Transition statement Next: Steps to Create and Use a Custom Tag Library
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-4. Steps to create and use a custom tag library RD7927.0
Notes:
There are two aspects to custom JSP tags: development and use. Development is
concerned with the design and implementation of the tag as a component, whereas use is
concerned with combining the functions of the tag with other elements in a JSP page to
effect the desired presentation.
5
Steps to create and use a custom tag library
To develop a tag, you need to:
Design your tags and attributes
Declare the tag in a tag library descriptor (TLD)
Develop a tag handler class
Develop helper classes for the tag (if needed)
To use a custom tag, the JSP needs to:
Include the tag library using the taglib directive
Code the custom tag with any needed attributes
Test your tags
class 1
class 2
helper
class
TLD
JSP
page
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-9
V4.0
Uempty
Instructor notes:
Purpose Explain tag libraries.
Details
Additional information
Transition statement Next: Tag Usage Example
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-5. Tag usage example RD7927.0
Notes:
This slide demonstrates the use of a JSP custom tag. The taglib directive (line 4) is
required. It specifies the URI of a descriptor for a set of tags to be used in the JSP page
and a prefix which will refer to the taglib in the current page. It is possible that a page might
use several sets of tags; a separate taglib directive would be required for each set.
The JSP custom tag <tl:date> is used near the end of the example. The tag displays the
current date in a full format. Notice how the prefix as specified in the taglib prefix attribute
(tl) is used to form the complete name of the tag.
6
Tag usage example
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 transitional//EN">
<HTML><HEAD>
<%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix=tl"
%>
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1
%>
<TITLE>Date Demo</TITLE>
</HEAD>
<BODY>
<h1>Date Demo</h1>
<P>Fully formatted date:
<tl:date format=full/>
</P>
</BODY></HTML>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-11
V4.0
Uempty
Instructor notes:
Purpose Provide an example of a tag in use.
Details
Additional information
Transition statement Next: JSP Page Without Custom Tags
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-6. JSP page without custom tags RD7927.0
Notes:
If the <tl:date> tag were not available, some Java code dealing with the system date would
need to be written as a scriptlet to provide the same function. The tag provides the
functionality of the Java code without the baggage of the specific coding implementation
and syntax details. The Web developer just wants the tag component to deliver the action
of providing a nicely formatted date.
7
JSP page without custom tags
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML><HEAD>
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<TITLE>Date Demo</TITLE>
</HEAD><BODY>
<h1>Date Demo</h1>
<P>Fully formatted date:
<% java.util.Locale locale =
pageContext.getRequest().getLocale();
java.text.DateFormat fmt =
java.text.DateFormat.getDateInstance
(java.text.DateFormat.FULL,locale);
String date = fmt.format(new java.util.Date()); %>
<%= date %>
</P>
</BODY></HTML>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-13
V4.0
Uempty
Instructor notes:
Purpose Show how much worse code without tags is.
Details
Additional information
Transition statement Next: Using Custom Tags with Application Developer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-7. Using custom tags with Application Developer RD7927.0
Notes:
The facilities of Page Designer can be used to select the tags that have been defined in the
TLD referenced by the taglib directive of JSP. The dialog box shows all the tags that are
going to be developed as part of this unit.
The same dialog can also be used to select tags from predefined tag libraries, such as the
JSP Standard Tag Library (JSTL). In this case, it automatically generates a <%@taglib>
tag.
8
Using custom tags with Application Developer
Page Designer has different ways of selecting a tag for
inclusion with JSP
Select JSP->Insert Custom
Drag Custom from JSP Tags drawer in Palette
Select desired tag from Insert Custom Tag dialog
1
2
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-15
V4.0
Uempty
Instructor notes:
Purpose Explain how Rational Application Developer supports tag use in JSP files.
Details
Additional information
Transition statement Next: JSP Standard Tag Library (JSTL)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-8. JSP Standard Tag Library (JSTL) RD7927.0
Notes:
The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that implement
general-purpose functionality common to Web applications, including iteration and
conditional processing, data management formatting, manipulation of XML, and database
access. Although you learn later in this unit how to create your own tags, be sure to always
consider existing tag libraries first, especially the JSTL, which is included with Rational
Application Developer as part of its support for JSP 2.0.
The Jakarta Project also makes available a wide selection of tag libraries. Some of these
are also included in Rational Application Developer, but the entire set may be downloaded
freely from http://jakarta.apache.org/taglibs/.
9
JSP Standard Tag Library (JSTL)
Encapsulates as tags core functionality of many Web applications
Supports tasks such as:
Flow (iteration and conditionals)
Manipulation of XML documents
Internationalization tags
SQL tags
J2EE 1.4 includes both JSP and JSTL
JSTL taglibs included with Rational Application Developer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-17
V4.0
Uempty
Instructor notes:
Purpose Explain and motivate use of JSTL.
Details
Additional information
Transition statement Next: Sample JSTL Tags
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-9. Sample JSTL tags RD7927.0
Notes:
10
Sample JSTL tags
Set a variable in a specific scope to a value
<c:set var="name" scope="scope" value="expression"/>
Display a value, or an alternative if the first value is null
<c:out value="expr" default="expr" escapeXml="boolean"/>
Example:
Hello <c:out value="${user.name}" default="Guest"/>!
Conditional execution
<c:choose>, <c:when> and <c:otherwise>
<c:choose>
<c:when test="${user.role == 'member'}">
<p>Welcome, member!</p>
</c:when>
<c:otherwise>
<p>Welcome, guest!</p>
</c:otherwise>
</c:choose>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-19
V4.0
Uempty
Instructor notes:
Purpose Give examples of some useful but simple JSTL tags.
Details
Additional information
Transition statement Next: ForEach Tag
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-10. forEach tag RD7927.0
Notes:
11
forEach tag
Provides flexible iteration through a set of items
Targets include:
Collections, Maps, Iterators, Enumerations
Arrays
Comma-separated values
SQL ResultSets
Example:
<table>
<c:forEach items="${customers}" var=cust">
<tr>
<td>${cust.name}</td>
<td>${cust.addr}</td>
</tr>
</c:forEach>
</table>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-21
V4.0
Uempty
Instructor notes:
Purpose Explore forEach tag.
Details
Additional information
Transition statement Next: Anatomy of a Tag
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-11. Anatomy of a tag RD7927.0
Notes:
Formally, the things called tags are really XML elements. In XML, the term tag refers to the
syntactic units, enclosed in < and > signs, which begin and end such elements. However,
as used in the JSP specification, the term tag refers to the entire element.
A tag may have name-value pairs associated with it. These are called attributes. It may
also have a body, which is the area between the start and the end tag. A tag that does not
have a body needs no end tag, but in that case its start tag should end with /> instead of >.
12
Anatomy of a tag
<tl:asis tab="5">
Instructions for logging in to the system:
(1)Enter your Patron identifier in ID field
(2)Enter assigned password in PW field
(3)Click on LOGIN button
</tl:asis>
Start tag
Body
(optional)
End tag
Attribute (optional)
Element
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-23
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Tag Examples
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-12. Tag examples RD7927.0
Notes:
In the fourth example, list is a list of objects with type domain.Customer, and the iterator
goes through them one at a time. In each look, the object which is currently selected is
called customer. Thus, this example would result in a list of customer names being
displayed on the browser.
13
Tag examples
Basic
<tl:fullText />
With attributes
<tl:code language="java/>
With attributes and a body
<tl:iterator times=10>
<p>"Hello world."</p>
</tl:iterator>
Defining scripting variables
<tl:iterator name="list" id="customer
type="domain.Customer">
<jsp:getProperty name="customer"
property="name" />
</tl:iterator>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-25
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Describing Tags to the JSP Container
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-13. Describing tags to the JSP container RD7927.0
Notes:
14
Describing tags to the JSP container
Done with the taglib descriptor (TLD)
XML file
Describes the tag library
Files use the .tld extension
Defines the syntax of the tags (actions)
Defines the attributes (if any) for the tags
Specifies if the attribute is optional or required
Specifies the Java class that implements the tag
Specifies if the tag allows or uses a body
Used by the JSP container to validate the JSP at compile time
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-27
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: General Format of the TLD (1 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-14. General format of the TLD (1 of 2) RD7927.0
Notes:
The taglib descriptor (TLD) is an XML file and contains a required XML declaration and
document type declaration (DTD) that defines the format of the files.
The version of the tab library (<tlib-version>), version of the JSP specification the tag
depends on (<jsp-version>), default prefix (<short-name>), and description
(<description>) are characteristics that apply to the entire tag library.
Each tag defined in the TLD is delineated by enclosing <tag> elements, which define the
name of the tag (<name>), its implementing class (<tag-class>), and how the tag body is
processed (<body-content>). In this example, the <body-content> tag declares that the
tag does not have a body.
15
General format of the TLD (1 of 2)
Defines the date tag
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd">
<tag>
<name>date</name>
<tag-class>com.ibm.library.tag.FormattedDate</tag-class>
<body-content>empty</body-content>
<description>Display current date</description>
</tag>
<description>Tag Library from IBM Library System
</description>
<tlib-version>1.0</tlib-version>
<short-name>ilib</short-name>
Required
Info about TLD
Tag Info
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-29
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: General Format of the TLD (2 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-15. General format of the TLD (2 of 2) RD7927.0
Notes:
This slide shows a second tag (date2) that is defined in the TLD. In this case, the
<body-content> element states that the body of the tag may contain JSP elements itself.
Attributes on the tag are specified by the <attribute> element. The date2 tag has one
attribute named format that must be specified.
16
General format of the TLD (2 of 2)
<tag>
<name>date2</name>
<tag-class>com.ibm.library.tag.FormatDate2</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
<attribute>
<name>format</name>
<required>true</required>
</attribute>
Action
name
Tag handler class
implementation
How to process the body
Attribute name
(multiple
allowed)
Optional (false) or
mandatory (true)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-31
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Location of TLD File
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-16. Location of TLD file RD7927.0
Notes:
The actual location of the TLD file could be in a JAR file with the implementing classes or
directly in the Web application. Note that the XML Schema location is specified in the TLD
and points to the location specified on the slide.
17
Location of TLD file
Resides in the META-INF directory or subdirectory when
deployed inside a JAR file
Resides in the WEB-INF directory or some subdirectory when
deployed directly into a Web application
XML schema is located at URL:
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-33
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: JSP Taglib Directive
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-17. JSP taglib directive RD7927.0
Notes:
The taglib directive is required to be placed in a JSP file in order to specify the location of
the TLD in the Web Project, as well as the prefix to be used for the tag inside this particular
file. The full name of the JSP tag element (in this case tl:date) is a combination of the prefix
(in this case, tl) and the value of the <name> element of the tag (in this case, date).
18
JSP taglib directive
Taglib directive tells your JSP the prefix to be used for a
specific JSP tag library
<!DOCTYPE >
<HTML>
<HEAD>
<%@ taglib uri="/WEB-INF/tld/taglib.tld" prefix="tl" %>

<TITLE>date test</TITLE>
</HEAD>
<BODY>

<tl:date format="full"/>

</BODY>
</HTML>
Taglib directive
Taglib usage
Location of TLD
Prefix for this JSP
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-35
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Tag Handler Base Classes
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-36 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-18. Tag handler base classes RD7927.0
Notes:
The tag handler class is defined by the <tag-class> element in the TLD and contains the
Java code that implements the tag. Tag handler classes must implement one of the four
interfaces other than JspTag shown in the diagram (JspTag is a convenience interface
with no methods). Which interface you choose to implement when you write the tag handler
class depends on the tasks that tag is required to perform.
For convenience, support classes are also provided. Tag handler classes which extend one
of the support classes will automatically implement one of the required interfaces.
SimpleTag and SimpleTagSupport are new in JSP 2.0 and require the developer to
override a single method, doTag(). Classic tags may still be developed (and special
circumstances may require their use), but they are more complex, require the
implementation of more methods, and may involve multi-step processing controlled by a
predetermined set of return codes.
19
Tag handler base classes
Tag handlers must implement specific
interfaces or extend specific classes, and
must override key methods
These classes all reside in
javax.servlet.jsp.tagext
JSP 2.0 introduced
SimpleTag
classic
tags
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-37
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information Simple tags do not permit scriptlets or expressions in their
bodies. Classic tags are still required if the body of the tag may include scripting.
Transition statement Next: Example Tag
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-38 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-19. Example tag RD7927.0
Notes:
In the following pages, you see how to build the tag handler class and tag library descriptor
associated with this tag.
20
Example tag
The <transform> tag allows page developers to transform the
contained text in two ways:
Convert it to upper case
Hide it
The tag has a required attribute mode with the following
values:
upper
hide
The value of the attribute can be taken from a runtime
expression
<m:transform mode="upper">
<P>This is text to be transformed.</P>
</m:transform>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-39
V4.0
Uempty
Instructor notes:
Purpose Introduce the tag which is developed over the next few charts.
Details
Additional information Be sure to stress the inherent flexibility of such a tag (many
more transformations could easily be developed) and its robustness (since letting an
expression control the attribute enables dynamic transformation).
Transition statement Next: Processing Tags with Attributes: How It Works
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-40 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-20. Processing tags with attributes: How it works RD7927.0
Notes:
Conceptually, as parts of a tag are processed by the JSP container, corresponding
methods in the tag handler class are executed.
As part of the initialization process, the setMode() method is executed to deliver the value
of the mode attribute. If the tag handler is a SimpleTag, all of the processing functions will
be coded in the doTag() method. This method has access to the body of the tag, and a way
to emit text back to the invoking page.
21
Processing tags with attributes: How it works
<m:transform mode="upper">
<P>This is text to be
transformed.</P>
</m:transform>
1) Initialize and set attributes
(setMode())
2) Call doTag() method
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-41
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: What Needs to Be Done?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-42 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-21. What needs to be done? RD7927.0
Notes:
What needs to be done to use a new tag?
First, a tag handler class needs to be developed. Then a <tag> entry is required in the TLD
to specify the name of the tag handler class, and the attribute needs to be defined.
Finally, you can test and use the new tag by including it in a JSP.
22
What needs to be done?
Create the TransformTag class
Update the TLD for the new date tag
Use the new <transform> tag in your JSPs
handler
class
TLD JSP
page
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-43
V4.0
Uempty
Instructor notes:
Purpose Provide an overview of the steps in tag development.
Details
Additional information
Transition statement Next: The TransformTag Class
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-44 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-22. The TransformTag class RD7927.0
Notes:
Here is the code for the tag handler class. Note the following:
The class extends SimpleTagSupport.
The attribute mode is present as a member field.
The setter method (setMode()) used to deliver the value of the attribute to the handler. No
getter method is required.
23
The TransformTag class
package com.ibm.library.tag;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class TransformTag extends SimpleTagSupport {
String mode = "";
public void setMode(String mode) {
this.mode = mode.toUpperCase();
}
// class continues on next page
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-45
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: The doTag() Method
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-46 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-23. The doTag() method RD7927.0
Notes:
The heart of tag processing a SimpleTag is the doTag() method. In this example, it
performs the following tasks:
1. Gets the body of the tag with getJspBody()
2. Puts the body into a String with invoke()
3. Transforms the body according to the mode attribute.
4. Writes the transformed body back to the JSP page.
5. Good practice would be to enclose both the invoke() and write() methods in try-catch
blocks, but these have been omitted to make the example more compact.
24
The doTag() method
public void doTag() throws JspException, IOException {
JspFragment body = getJspBody();
StringWriter oldbody = new StringWriter();
String newbody = null;
body.invoke(oldbody);
if (mode.equals("UPPER")) {
newbody = oldbody.toString().toUpperCase();
} else if (mode.equals("HIDE")) {
newbody = "";
} else {
newbody = oldbody.toString();
}
JspWriter out = getJspContext().getOut();
out.write(newbody);
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-47
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: The Taglib Descriptor
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-48 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-24. The taglib descriptor RD7927.0
Notes:
The main purpose of the taglib descriptor is to map the tag to its handler class, and to
specify the attributes that must be delivered.
25
The taglib descriptor
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">
<description>Tag Library for Library System</description>
<tlib-version>1.0</tlib-version>
<short-name>ilib</short-name>
<tag>
<name>transform</name>
<tag-class>com.ibm.library.tag.TransformTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>mode</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-49
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Using the <transform> Tag
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-50 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-25. Using the <transform> tag RD7927.0
Notes:
This chart shows the text of a JSP page which will test the tag (META tags have been
deleted to save space). Note the JSP taglib directive which defines the location and prefix
for the taglib, and note the use of the prefix when using the tag.
26
Using the <transform> tag
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="WEB-INF/tld/mytags.tld" prefix="m" %>
<TITLE>transformDemo.jsp</TITLE>
</HEAD>
<BODY>
<H1>Demonstrate &lt;transform&gt; tag</H1>
<m:transform mode="UPPER">
<P>This is text to be
transformed</P>
</m:transform>
<P>This text is not
to be transformed</P>
</BODY>
</HTML>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-51
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-52 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-26. Packaging RD7927.0
Notes:
In the examples the tag handler class resides in a package within the Web project that uses
it. This is expedient for developing and testing JSP tags, but does not let them be easily
shared with other projects. Placing the tag handler classes in a JAR file allows them to be
easily used in other projects.
In the screen capture, notice that a URI of http://www.ibm.com/Library/tags has been
created to reference the TLD at location /WEB-INF/tld/taglib.tld. The URI can be
referenced in the page directive of a JSP using this tag library. The Web Deployment
Descriptor stores the map from URI to TLD location. It can be edited in the Tag Lib
References area of the Variables tab.
27
Packaging
To facilitate reuse, the tag handler classes can be packaged
together
Place the class files in a JAR
Import the TLD into /WEB-INF/tld
Import the JAR into /WEB-INF/lib
An additional option is to
package the TLD with the
class files JAR
Application Developer provides
support for JSP tag library
resource references
Web Deployment Descriptor editor
Variables tab
Allows URI to be specified to reference the TLD
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-53
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-54 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-27. Checkpoint RD7927.0
Notes:
Write down your answers here:
28
Checkpoint
1. What are some of the advantages of JSP custom tags?
2. What are the major steps that must be performed during JSP custom
tag development?
3. How are attributes values processed in a tag handler class?
4. What method of the SimpleTag interface does the main work of
processing a tag?
5. What is the purpose of the JSP taglib directive?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-55
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-56 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-28. Checkpoint solutions RD7927.0
Notes:
29
Checkpoint solutions
1. What are some of the advantages of JSP custom tags?
Make JSPs easier to develop, test, and maintain
Web developer can focus on presentation (role-based
developmental
Presentation logic is reusable
2. What are the major steps that must be performed during JSP custom
tag development?
Design tags and attributes
Write tag handler class
Construct or modify TLD
Test in a JSP
3. How are attribute values processed in a tag handler class?
Attribute values are processed in a tag handler class through
JavaBean-like setter methods.
4. What method of the SimpleTag interface does the main work of
processing a tag?
doTag()
5. What is the purpose of the JSP taglib directive?
The taglib directive describes the location of the TLD and designates
the tag prefix.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-57
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-58 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 22-29. Unit summary RD7927.0
Notes:
30
Having completed this unit, you should be able to:
Describe the advantages of using JSP custom tags
List the major steps in developing and using JSP custom tags
Develop basic tag handler classes to implement JSP custom
tags
Create and modify taglib descriptor files
Package JSP taglib implementation classes and taglib
descriptor files
Understand the uses of the JSTL
Name some of the tags included in the JSTL and their
purposes
Having completed this unit, you should be able to:
Describe the advantages of using JSP custom tags
List the major steps in developing and using JSP custom tags
Develop basic tag handler classes to implement JSP custom
tags
Create and modify taglib descriptor files
Package JSP taglib implementation classes and taglib
descriptor files
Understand the uses of the JSTL
Name some of the tags included in the JSTL and their
purposes
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 22. JSP Custom Tags 22-59
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
22-60 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-1
V4.0
Uempty
Unit 23.JSP Tag Files
Estimated time
00:15
What this unit is about
This unit describes the creation and use of JSP tag files.
What you should be able to do
After completing this unit, you should be able to:
Describe the use of JSP tag files
Call a tag file from a JSP
Pass body content, parameters and fragments to a tag file
Create a tag file and use the tag file directives
Package a tag file
How you will check your progress
Accountability:
Checkpoint
Machine exercises
References
http://java.sun.com/products/jsp
JavaServer Pages Technology
http://jcp.org/en/jsr/detail?id=152
JSR 152: JavaServer Pages 2.0 Spec. (section 8)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Describe the use of JSP tag files
Call a tag file from a JSP
Pass body content, parameters and fragments to a tag file
Create a tag file and use the tag file directives
Package a tag file
After completing this unit, you should be able to:
Describe the use of JSP tag files
Call a tag file from a JSP
Pass body content, parameters and fragments to a tag file
Create a tag file and use the tag file directives
Package a tag file
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-3
V4.0
Uempty
Instructor notes:
Purpose This unit introduces the basic concepts of JSP tag files. After completion of this
unit, the learner should be able to write a simple tag file in IBM Rational Application
Developer.
Details The module starts out by an overview of a tag file and how to call one. It is then
broken into 2 parts:
1. Caller JSP: What you can pass to a tag file
2. Tag File: Directives and objects you can use in a tag file
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-2. Overview of tag files RD7927.0
Notes:
3
Overview of tag files
Another way to build custom actions
Tag files are JSPs with .tag or .tagx extensions
Allows non-Java developers to create reusable custom actions
Are automatically interpreted by the JSP container when
placed in the /WEB-INF/tags folder
Custom action name is the same as the tag file name
Can be further organized in sub-folders of
/WEB-INF/tags
Tag files are separate files that are called from JSPs
Caller JSP
<info:TagFile1 />
<info:TagFile2>
body content
</info:TagFile2>
TagFile2.tag
TagFile1.tag
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-3. Calling a tag file from a JSP RD7927.0
Notes:
4
Calling a tag file from a JSP
Resembles the invocation of a custom action
Tag files are automatically compiled into SimpleTags
More powerful than a <jsp:include> that can only accept string
parameters in the request
The tag file has access to implicit objects
The tag file can be passed
Body content: Content in between the begin and end tag
Parameters
Fragments: Individually named body content
For example to call details.tag from a caller JSP
<%@taglib tagdir="/WEB-INF/tags"
prefix="info" %>
<info:details loanedCopy="${item}"/>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-4. Body content from caller JSP RD7927.0
Notes:
scriptless can have EL and actions, just no scripting.
tagdependent will be interpreted by the tag file.
empty checks to make sure the body content is empty.
5
Body content from caller JSP
Body content can be: scriptless, tagdependent or empty
Tag files can use <jsp:doBody/> to use the body content
Caller JSP
<info:toUpper>
Uppercase this text
</info:toUpper>
toUpper.tag (Tag file)
<%@ tag body-content="scriptless"%>
<p style="text-transform:uppercase">
<jsp:doBody/>
</p>
Body
Content
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-5. Parameters from caller JSP RD7927.0
Notes:
6
Parameters from caller JSP
Passed as attributes to the tag file
Matches an attribute, with the same name, in the tag file
<info:details loanedCopy="${item}"/>
Can be a dynamic list of attributes
Handled in the tag file by a map, thus order is not
guaranteed
Can be mixed with defined attributes
<info:details
dyna1="first"
loanedCopy="${item}"
dyna2="second"/>
Defined parameter
mixed in with 2
dynamic parameters
Parameter
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-11
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-6. Fragments from caller JSP RD7927.0
Notes:
7
Fragments from caller JSP
Enable the calling page to pass in named fragments of body
content
<jsp:body> is used to define the main body content
<info:fragmentTest>
<jsp:attribute name="headerFragment">
<h1>Welcome to the IBM Library System </h1>
</jsp:attribute>
<jsp:attribute name="footerFragment">
System has ${library.size} books
</jsp:attribute>
<jsp:body>
${item.title} ${item.author}
</jsp:body>
</info:fragmentTest>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-13
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-7. Tag directive in tag file RD7927.0
Notes:
8
Tag directive in tag file
Attribute list for the directive
display-name
body-content: empty, scriptless or tagdependent
dynamic-attributes: name of the attribute map
small-icon
large-icon
description
example
language: scripting language
import: list of imports
pageEncoding
isELIgnored: true of false
For example
<%@ tag body-content="empty"%>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-15
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-8. Attribute directive in tag file RD7927.0
Notes:
9
Attribute directive in tag file
Maps incoming parameters to variables
Attribute list for the directive
name
required: true or false
fragment: true or false
rtexprvalue: true or false
type: type of the attribute
description
For example
<%@ attribute name="loanedCopy" required="true"
type="com.ibm.library.model.LoanedCopy"%>
Dynamic attribute map, is defined in the tag directive
<%@tag dynamic-attributes="elements" %>
<c:forEach var="element" items="${elements}" >
${element.key} : ${element.value}
</c:forEach>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-17
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-9. Variable directive in tag file RD7927.0
Notes:
10
Variable directive in tag file
Exposes variables to the calling page
A name can be given to the attribute or can be assigned from
an attribute
If assigned from an attribute, an alias needs to be defined
to reference the attribute within the tag file
Attribute list for the directive
name-given or name-from attribute, with an alias
variable-class
scope: AT_BEGIN, AT_END or NESTED
description
For example:
<%@ variable name-given="returnValue"
scope="AT_BEGIN" %>
<c:set var="returnValue" value="5%
interest"/>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-19
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-10. Implicit objects available in a tag file RD7927.0
Notes:
11
Implicit objects available in a tag file
Collection of objects available to the tag file
request: ServletRequest or HttpServletRequest
response: ServletResponse or HttpServletResponse
jspContext: JspContext for this tag file
session: HttpSession
application: ServletContext
out: JspWriter
config: ServletConfig
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-21
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-11. Example of calling a tag file RD7927.0
Notes:
Tag files can contain a tag directive versus a page directive.
A body-content of empty checks to make sure the tag is not wrapping some text.
The type parameter enforces the type of the attribute passed in.
Tag invocation:
The page that calls the tags includes a taglib directive with a tag attribute that indicates
the location of the tags.
The attribute defined in the tag files is simply referenced
12
Example of calling a tag file
Tag invocation in ListItems.jsp (Caller JSP)
<%@taglib tagdir="/WEB-INF/tags"
prefix="info" %>
<info:details loanedCopy="${item}"/>
Tag definition in details.tag (Tag file)
<%@ tag body-content="empty"%>
<%@ attribute name="loanedCopy" required="true"
type="com.ibm.library.model.LoanedCopy"" %>
<h1>Times Renewed = ${loanedCopy.timesRenewed} </h1>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-23
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-12. Tag file with body content and a fragment RD7927.0
Notes:
13
Tag file with body content and a fragment
Tag files can be passed fragments and evaluate the
separately, using <jsp:invoke fragment="fragmentName"/>
Calling JSP
<info:fragmentTest>
<jsp:attribute name="moreContent">
Fragment 1</jsp:attribute>
<jsp:body>Body content
</jsp:body>
</info:fragmentTest>
fragmentTest.tag
<%@ attribute name="moreContent"
fragment="true"%>
<jsp:invoke fragment="moreContent" />
<jsp:doBody/>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-25
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-13. Tag file packaging RD7927.0
Notes:
Tag files can be organized in subfolders of /WEB-INF/tags as well.
14
Tag file packaging
A tag file is recognized by the container if placed in the
/WEB-INF/tags/ folder
Tag file does not need TLD
At tag file placed in the /META-INF/tags folder of a JAR
file requires a TLD
The JAR file is placed in the /WEB-INF/lib folder
Tags can also be packaged as compiled Java classes
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-27
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-14. Checkpoint RD7927.0
Notes:
Write down your answers here:
15
Checkpoint
1. Where must a tag file placed to be automatically picked up
by the JSP container?
2. Why use a tag file instead of writing a custom tag handler?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-29
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-15. Checkpoint solutions RD7927.0
Notes:
16
Checkpoint solutions
1. Where must a tag file placed to be automatically picked up
by the JSP container?
The /WEB-INF/tags folder.
2. Why use a tag file instead of writing a custom tag handler?
Allows non-Java developers to create reusable custom
actions. Also externalizes any HTML and layout information
that may creep into a tag handler class.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-31
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 23-16. Unit summary RD7927.0
Notes:
17
Having completed this unit, you should be able to:
Describe the advantages of using JSP custom tags
List the major steps in developing and using JSP custom tags
Develop basic tag handler classes to implement JSP custom
tags
Create and modify taglib descriptor files
Package JSP taglib implementation classes and taglib
descriptor files
Understand the uses of the JSTL
Name some of the tags included in the JSTL and their
purposes
Create and call a tag file from a JSP
Having completed this unit, you should be able to:
Describe the advantages of using JSP custom tags
List the major steps in developing and using JSP custom tags
Develop basic tag handler classes to implement JSP custom
tags
Create and modify taglib descriptor files
Package JSP taglib implementation classes and taglib
descriptor files
Understand the uses of the JSTL
Name some of the tags included in the JSTL and their
purposes
Create and call a tag file from a JSP
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 23. JSP Tag Files 23-33
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
23-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-1
V4.0
Uempty
Unit 24.Servlet Filtering
Estimated time
00:45
What this unit is about
This unit describes the Servlet Filtering feature of the Servlet API,
Version 2.4.
What you should be able to do
After completing this unit, you should be able to:
Describe the processing flow for filters
List the Servlet API interfaces and support objects used to
implement filters
Create a new filter using Rational Application Developer
Create and modify deployment descriptor entries for filters
Develop a basic filter
Develop a filter that blocks normal filter chain execution
Develop a filter that uses a wrapped custom request or response
object
How you will check your progress
Accountability:
Checkpoint
Lab exercises
References
http://java.sun.com/j2ee/1.4/docs/api/index.html
Java2 Platform Enterprise Edition, v 1.4 API
Specification
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/
JSR-000154 JavaTM Servlet 2.4 Specification
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-1. Unit objectives RD7927.0
Notes:
This unit provides an introduction to servlet filters. At the end of the unit you are able to
create and deploy servlet filters with Rational Application Developer.
2
After completing this unit, you should be able to:
Describe the processing flow for filters
List the Servlet API interfaces and support object used to
implement filters
Create a new filter using Rational Application Developer
Create deployment descriptor entries for a filter
Develop a basic filter using the appropriate interfaces
Develop a filter that blocks normal filter chain execution
Develop a filter using a wrapped custom response object
After completing this unit, you should be able to:
Describe the processing flow for filters
List the Servlet API interfaces and support object used to
implement filters
Create a new filter using Rational Application Developer
Create deployment descriptor entries for a filter
Develop a basic filter using the appropriate interfaces
Develop a filter that blocks normal filter chain execution
Develop a filter using a wrapped custom response object
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Introducing Filters
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-2. Introducing filters RD7927.0
Notes:
Some Web servers like Apache, IIS, and Netscape have implemented proprietary filtering
or filtering-like schemes. The servlet filtering API is a J2EE standard (since J2EE 1.3).
3
Introducing filters
Reusable components
Transform (or filter) the content of HTTP requests, responses, and
headers
Can be configured into chains of multiple filters
Are indirectly invoked by client request for a Web resource
Requested Web resource is at the end of the chain
Types of functionality:
Process the request for a resource before it is invoked
Process the response for a resource after it is invoked
Modify the response or request object for a Web resource by
wrapping the objects in a custom object
Transfer control to next filter or Web resource in chain
Block execution of the filter chain
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Typical Uses of Filters
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-3. Typical uses of filters RD7927.0
Notes:
Many other uses are possible. Tokenizing filters, for example, might be used with mobile
devices to convert the output of an HTML tag to a special bytecode the device can
interpret, in order to compress the response stream.
The Servlet Filtering API is included in the Java Servlet Specification, and can be viewed
on the Web at http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html.
Filters can be thought of pluggable components that can process common services in a
standard way without requiring changes to the core processing code of the filtered servlet.
The function provided by filters can be added or deleted by changing only the deployment
descriptor and not the core processing code of the servlet. Filters can be added or removed
without changing the core function of the filtered code, thus allowing a set of services to be
configured at run time, rather than during development. Instead of coding conditional logic
in a servlet to use a set of ancillary services based on the settings of some flags, one can
simply add or remove filters (and their corresponding services) by configuring the
deployment descriptor.
4
Typical uses of filters
The Servlet Filtering Specification notes these as examples of
typical filter uses:
Authentication filters
Logging and auditing filters
Image conversion filters
Data compression filters
Encryption filters
Tokenizing filters
Filters that trigger resource access events
XSLT filters to transform XML content
MIME-type chain filters
Caching filters
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Filter Processing Flow
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-4. Filter processing flow RD7927.0
Notes:
Filters are not explicitly seen by the client user. They are invoked when there is a request
for a client resource and that client resource has been configured to use filters. Entries in
the Web deployment descriptor describe which filters are used for a particular resource;
this is covered in more detail later in the unit.
At execution time, the filter typically accesses and possibly modifies the request object
(preprocessing), transfers control to the Web resource using the doFilter() method of the
FilterChain class, and then accesses (and possibly modify) the response object (post
processing) after the doFilter() method completes. Each of these steps is performed within
the same method in the filter. As part of the processing, the filter might query, modify, or
customize the request and response objects to perform its function. The client request and
response are passed to the next filter in the chain as parameters to doFilter().
5
Filter processing flow
Web Resource Requested by Client
Request Response
Access/Modify Request
doFilter()
Access /Modify Response
Filter
Client Request for Web Resource
Container
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Filter Chain Processing
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-5. Filter chain processing RD7927.0
Notes:
The filter chain is a key concept in servlet filtering.
6
Filter chain processing
Filters can be configured in a chain
A FilterChain object describes the chain
Filters are invoked using nested calls
Web container invokes doFilter() in first filter in chain
Class: Implementation of javax.servlet.Filter
Parameters:
Request of type ServletRequest
Response of type ServletResponse
Chain of type FilterChain
First filter in chain calls doFilter() to invoke next filter in chain
Referenced from input FilterChain object
Class: javax.servlet.FilterChain
Parameters:
Request of type ServletRequest
Response of type ServletResponse
Last entry in the chain is the Web resource
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-11
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: doFilter() Nested Calls
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-6. doFilter() nested calls RD7927.0
Notes:
This diagram illustrates how filters are nested. The client request is for the FilterServlet
resource. The first filter in the chain (FirstFilter) has the chain of the filter passed (by the
container) as an input parameter to doFilter(). The filter then uses the doFilter() method of
the chain object to call SecondFilter. SecondFilter likewise uses the same mechanism,
but it will execute the requested Web resource which is at the end of the chain. Upon return
from the end of the chain, control transfers back through the nested calls. The request and
response objects are passed as parameters on the chain.doFilter() methods.
7
doFilter() nested calls
doFilter() {
chain.doFilter()
}
doPost() {

.
}
doFilter() {
chain.doFilter()
}
FirstFilter
SecondFilter
FilteredServlet
http://example.com/app/FilteredServlet
Request
Response
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-13
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Typical doFilter() Pattern
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-7. Typical doFilter() pattern RD7927.0
Notes:
This is a typical processing flow used within the doFilter() method of each of the filters.
Note that if a filter chooses to end the chain, it is responsible for creating the response to be
sent back to the client. Subsequent filters in the chain, which might have filled in the
response object during the normal processing flow, are not available.
8
Typical doFilter() pattern
Examine request object
Possibly wrap request or response object in new custom
object
Invoke next filter in chain with doFilter() method
Possibly with wrapped objects
May end chain by not performing this step
Filter must complete response object
Process response object
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-15
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Implementing a Filter
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-8. Implementing a filter RD7927.0
Notes:
To implement a filter, the class must be created and entries must be made in the
deployment descriptor file (web.xml).
9
Implementing a filter
Create a class that implements the javax.servlet.Filter interface
Implement methods:
init()
doFilter()
destroy()
Describe the filter in the deployment descriptor with the filter
element
Configure the chaining configuration of the filter in the
deployment descriptor with the filter-mapping element
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-17
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-9. Application Developer filter support RD7927.0
Notes:
Application Developer can create a skeleton of an implementing class for a filter and create
entries in web.xml file.
10
Application Developer filter support
Creating a filter in Web Perspective
Right-click the Web project and click New -> Filter
Creates a class that implements javax.servlet.Filter
Creates the following methods in the class:
init
doFilter
destroy
Creates entries in deployment descriptor to define filter:
filter
filter-mapping
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-19
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Creating a New Filter in Application Developer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-10. Creating a new filter in Application Developer RD7927.0
Notes:
The dialogs used in Application Developer to create a filter are shown in the slide.
11
Creating a new filter in Application Developer
Click Next.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-21
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Now you will look at some of the Java Servlet API interfaces and
support classes that are used to construct servlet filters.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-11. The javax.servlet.Filter interface RD7927.0
Notes:
A class of the filter must implement the three methods of the javax.servlet.Filter interface.
Skeletons for these methods are created by the Application Developer new filter dialogs;
you just need to fill in the code.
12
The javax.servlet.Filter interface
Three methods comprise the interface:
init() throws ServletException
Purpose: To perform filter initialization
Called by container to indicate filter is being placed in service
Parameter:
config of type FilterConfig
doFilter() throws ServletException, IOException
Purpose: To perform the filtering
Called by the container each time a request/response pair is passed through the
chain due to a client request for a resource at the end of the chain
Parameters:
Request of type ServletRequest
Response of type ServletResponse
Chain of type FilterChain
destroy()
Purpose: To perform filter cleanup.
Called by container to indicate filter is being placed out of service
No parameters
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-23
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: The javax.servlet.FilterConfig Interface
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-12. The javax.servlet.FilterConfig interface RD7927.0
Notes:
Remember that a FilterConfig object is a passed by the container as a parameter of the
init() method of the javax.servlet.Fitler class. You can use the methods of that object as
shown in the slide in the class of the filter. Two common uses of the configuration object are
to access with the init parameters of the filter (which are set in the web.xml file) and get the
servlet context.
13
The javax.servlet.FilterConfig interface
There are four getter methods in the interface:
getFilterName()
Returns the String name of the filter
getInitParameter()
Returns the the String value of a initialization parameter
Input: Name of type String
getInitParameterNames()
Returns an enumeration of String with the names of the initialization
parameters
getServletContext()
Returns a reference to the ServletContext in which the filter is
operating
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-25
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: The javax.servlet.FilterChain Interface
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-13. The javax.servlet.FilterChain interface RD7927.0
Notes:
An object of FilterChain type is supplied by the Web container to the doFilter() method of
the filter. Use that object as the reference for the doFilter() method when the filter is ready
to pass control to the next filter in the chain.
14
The javax.servlet.FilterChain interface
The interface consists of one method:
doFilter() throws ServletException
Purpose: Invoke the next filter in the chain
Called by the container each time a request/response pair is passed
through the chain due to a client request for a resource at the end of
the chain
Inputs:
Request of type ServletRequest
Response of type ServletResponse
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-27
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next you look at how to describe the filter to the container
through the filter and filter-mapping element entries in the deployment descriptor file.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-14. Describing the filter RD7927.0
Notes:
If you use the new filter function of the Application Developer, entries are added to the
web.xml file for the filter you are creating. These entries may need to be modified if you
add new filter mappings or change init-parameters, as just a few examples.
15
Describing the filter
Filters are described in the deployment descriptor (web.xml)
Structure of the filters describing elements
<filter>: describes the filter
<filter-name>: Name of the filter
<filter-class>: Name of the implementing class
<init-param>: Describes initialization parameters of the filter
<param-name>: The initialization parameter name
<param-value>: The initialization parameter value
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-29
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Example Of A Filter Description
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-15. Example of a filter description RD7927.0
Notes:
Note that this filter has two init parameters, __FORM_NAME and num.
16
Example of a filter description
<filter>
<display-name>FormChecker</display-name>
<filter-name>FormChecker</filter-name>
<filter-class>
com.ibm.filters.FormChecker
</filter-class>
<init-param>
<param-name>__FORM_NAME</param-name>
<param-value>Prime Finder</param-value>
</init-param>
<init-param>
<param-name>num</param-name>
<param-value>Number</param-value>
</init-param>
</filter>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-31
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Describing the Filter Mapping
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-16. Describing the filter mapping RD7927.0
Notes:
The filter mappings essentially describe the filter chain. When a client request for a Web
resource is made, the container consults the filter-mapping entries of the deployment
descriptor to find a match on either the servlet-name or url-pattern element and determines
the corresponding filters for the resource.
Filter mappings can also include a <dispatcher> element which determines when the
mapping is active. This is discussed later in this presentation.
17
Describing the filter mapping
Filter mappings are described in the deployment descriptor
(web.xml)
Structure of the mapping elements of the filter
<filter-mapping>: Describes the filter
<filter-name>: Name of the filter to be mapped
<servlet-name>: Name of the resource to apply this filter
OR
<url-pattern>: URL pattern of the resource to apply this filter
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-33
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Examples of Filter Mapping
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-17. Examples of filter mapping RD7927.0
Notes:
The first filter, Logger, is mapped with the <servlet-name> element and filters the Prime
servlet.
The second filter, WelcomeTrailer, is configured with the <url-pattern> element and filters
/Welcome.jsp.
18
Examples of filter mapping
<filter-mapping>
<filter-name>Logger</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>WelcomeTrailer</filter-name>
<url-pattern>/Welcome.jsp</url-pattern>
</filter-mapping>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-35
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Configuring Filters with Application Developer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-36 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-18. Configuring filters with Application Developer RD7927.0
Notes:
As an alternative to editing the source view of the web.xml deployment descriptor, you can
use the Filters tab of the Deployment Descriptor Editor to generate the appropriate XML
elements in the web.xml file. Note the portrayal of the filters (and their initialization
parameters and mappings) in the Project Explorer.
19
Configuring filters with Application Developer
Configure filters in the Web Deployment Descriptor Editor
Filters tab
Source tab
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-37
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Configuring Filter Chaining
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-38 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-19. Configuring filter chaining RD7927.0
Notes:
A Web resource might have multiple filters. This slide describes the rules to determine what
order the filters are placed in the chain.
20
Configuring filter chaining
Determined by order of filter-mapping elements in the
deployment descriptor
Last filter in chain invokes the requested Web resource
Rules:
First, get filters that match url-pattern element of requested
Web resource
Second, get filters that match servlet-name element of
requested Web resource
In each case, the order in the chain of the filter is determined
by its order in the deployment descriptor file
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-39
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Example of Configuring Filter Chaining
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-40 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-20. Example of configuring filter chaining RD7927.0
Notes:
You want to determine the filter chaining order for the Prime servlet. Following the rules
from the previous slide:
The url-pattern element for Logger specifies that all URLs match it.
The servlet-name elements for the Prime servlet are FormChecker and PrimeTrailer, per
their order of appearance in the deployment descriptor file.
21
Example of configuring filter chaining
<filter-mapping>
<filter-name>FormChecker</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Logger</filter-name>
<url-mapping>/*</url-mapping>
</filter-mapping>
<filter-mapping>
<filter-name>PrimeTrailer</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
Mapping Order for Prime Servlet:
1. Logger
2. FormChecker
3. PrimeTrailer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-41
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Configuring Filters for Reuse
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-42 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-21. Configuring filters for reuse RD7927.0
Notes:
If possible, you should design a filter to be reused. One way to accomplish this is to use
initialization parameters to specify data to be used by the filters. Remember that a filter
might be used for a given resource by multiple clients, so the filter classes should be written
following general thread safe guidelines, such as avoiding the use of instance variables to
maintain state.
22
Configuring filters for reuse
Filters are designed to be reusable components
Same implementation class can be used for different filters
Different filter-name element
Possibly different init-param element
Container instantiates an instance of the class for each <filter>
element
public class AuditFilter implements Filter {
private int mode = 0;
public void init(FilterConfig arg0) throws ServletException {
String modeStr = arg0.getInitParameter("mode");
if (modeStr.equals("FULL")) {
mode = FULL;
}
...
}
...
<init-param>
<param-name>mode</param-name>
<param-value>FULL</param-value>
</init-param>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-43
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Example of Configuring Filter Reuse
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-44 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-22. Example of configuring filter reuse RD7927.0
Notes:
Here is one class, com.ibm.filters.Trailer, used by different filters, WelcomeTrailer and
DatabaseTrailer. Note that the <init-param> elements are different for each of the filter
instances.
23
Example of configuring filter reuse
<filter>
<filter-name>WelcomeTrailer</filter-name>
<filter-class>com.ibm.filters.Trailer</filter-class>
<init-param>
<param-name>msg</param-name>
<param-value>
Watch for our new Web Site!
</param-value>
</init-param>
</filter>
<filter>
<filter-name>DatabaseTrailer</filter-name>
<filter-class>com.ibm.filters.Trailer</filter-class>
<init-param>
<param-name>msg</param-name>
<param-value>
Sorry, but the database is currently down.
</param-value>
</init-param>
</filter>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-45
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Filters with RequestDispatcher
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-46 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-23. Filters with RequestDispatcher RD7927.0
Notes:
Earlier versions of the servlet specification did not clarify whether filters needed to be
invoked when requests were redirected using RequestDispatcher: that is, whether filters
can be invoked using forward() or include() requests. Servlet 2.4 provides the ability to
configure filters that are invoked with forward() and include() calls. This can be done by
using the new <dispatcher> element in the deployment descriptor.
24
Filters with RequestDispatcher
Ability to configure filters that are invoked under
RequestDispatcher with forward() and include() calls
R
e
q
u
e
s
t
Filters
Forward / Include
Filters
Web
resource
Filters
R
e
sp
o
n
se
R
eq
ue
st
R
esponse
Web
resource
Web
resource
Web
resource
Forward / Include
Servlet v2.4
Servlet v2.3
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-47
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Dispatcher Element
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-48 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-24. Dispatcher element RD7927.0
Notes:
These elements may be added manually to the deployment descriptor (web.xml) source, or
they may be chosen when adding mappings from the Filter tab of the deployment
descriptor editor.
25
<filter-mapping>
<filter-name>Customer
Filter</filter-name>
<url-pattern>/customers/*</url-
pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
Dispatcher element
New <dispatcher> element in the Deployment Descriptor:
REQUEST
Filter if request is directly from a client
FORWARD
Filter if request is from RequestDispatcher.forward() method
INCLUDE
Filter if request is from RequestDispatcher.include() method
ERROR
Filter if request is due to error redirection mechanism
REQUEST is the default when no <dispatcher> element
<filter-mapping>
<filter-name>Account
Filter</filter-name>
<servlet-
name>CustomerServlet</servlet-name>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-49
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement You will now look at sample code for three filters.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-50 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-25. Filter code examples RD7927.0
Notes:
For the remainder of the unit, three example filters will be described.
26
Filter code examples
Example filters:
Logger: A simple filter that performs elapsed execution
time logging for a servlet
FormChecker: A filter to check form syntax; blocks
execution of the chain if form is not correct
Trailer: A filter that appends a message to the end of a
Web resource response page; uses a custom response
object
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-51
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information If students carp about the uninformative parameter names used
in the examples (arg0, arg1, ...) point out that these are the names generated by the
Rational Application Developer Servlet wizard.
Transition statement Next: Logger Filter: Function Description
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-52 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-26. Logger filter: Function description RD7927.0
Notes:
The Logger filter displays the execution duration time of the Web resource that it filters in
the Web server event log.
27
Logger filter: Function description
A simple logging filter
Calculates execution time of the servlet in milliseconds
Displays the time in the event log of the server
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-53
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Logger Filter: Deployment Descriptor
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-54 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-27. Logger filter: Deployment Descriptor RD7927.0
Notes:
28
Logger filter: Deployment Descriptor
<filter>
<filter-name>Logger</filter-name>
<display-name>Logger</display-name>
<filter-class>
com.ibm.filters.Logger
</filter-class>
</filter>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-55
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Logger Filter: init() and destroy() Methods
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-56 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-28. Logger filter: init() and destroy() methods RD7927.0
Notes:
The init() method copies the FilterConfig object provided by the container to an instance
variable for later use in doFIlter().
29
Logger filter: init() and destroy() methods
package com.ibm.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Logger implements Filter {
FilterConfig config;
public void init(FilterConfig arg0)
throws ServletException {
config = arg0;
}
public void destroy() {
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-57
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Logger Filter: doFilter() Method
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-58 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-29. Logger filter: doFilter() method RD7927.0
Notes:
Note that this method has the three parts typical of a doFilter() pattern: process request,
transfer control to the next filter or Web resource, and process the response.
30
Logger filter: doFilter() method
public void doFilter (ServletRequest arg0,
ServletResponse arg1, FilterChain arg2)
throws ServletException, IOException {
long before = System.currentTimeMillis();
arg2.doFilter(arg0, arg1);
long duration = System.currentTimeMillis()- before;
String msg = Servlet duration: " +
duration + milliseconds";
config.getServletContext().log(msg);
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-59
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Logger Filter: How It Works
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-60 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-30. Logger filter: How it works RD7927.0
Notes:
If it is important that only the servlet be timed, care should be taken to make sure that
Logger is last in the list of filters in web.xml.
31
Logger filter: How it works
Gets timestamp from system
Uses the doFilter() method of FilterChain object to invoke
next filter
Upon return from doFilter(), calculates duration
Composes message with duration
Uses the config object (FilterConfig) to get the servlet context
Uses the ServletContext.log() method to write message to
the event log of the servlet
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-61
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: FormChecker Filter: Function Description
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-62 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-31. FormChecker filter: Function description RD7927.0
Notes:
This filter illustrates how a filter can block the normal flow of the filter chain by testing for
some condition and simply not invoking the chain based on the results. In this case, the
filter is responsible for filling in the response, which it does by forwarding to a JSP.
32
FormChecker filter: Function description
Checks that specified fields in a form have non-empty values
Filters a servlet that is the Action URL for a FORM tag
Field names are entered as the init-param names of the filter
Example: <param-name>firstname</param-name>
Field labels are entered as the filters init-param values
Example: <param-value>First Name</param-value>
Parameter name __FORM_NAME is reserved
Value is the name of the form (for example, Order Entry
Form)
If one or more errors is found, the filter forwards the list of
missing fields to a JSP page that lists the name
of the form and the form fields that are missing or
have empty values
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-63
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: FormChecker Filter: Deployment Descriptor
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-64 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-32. FormChecker filter: Deployment descriptor RD7927.0
Notes:
The __FORM_NAME init-param specifies the name of the form, Prime Finder.
The num init-parm corresponds to a required test input field named num on the form.
The filter is mapped to the Prime servlet, which generates prime numbers.
33
FormChecker filter: Deployment descriptor
<filter>
<filter-name>FormChecker</filter-name>
<display-name>FormChecker</display-name>
<filter-class>com.ibm.filters.FormChecker</filter-
class>
<init-param>
<param-name>__FORM_NAME</param-name>
<param-value>Prime Finder</param-value>
</init-param>
<init-param>
<param-name>num</param-name>
<param-value>Number</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FormChecker</filter-name>
<servlet-name>Prime</servlet-name>
</filter-mapping>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-65
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: FormChecker Filter: init() and destroy() Methods
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-66 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-33. FormChecker filter: init() and destroy() methods RD7927.0
Notes:
As with the previous example, FormChecker implements the init() and destroy() methods
in a way typical of many other filters. The config object is used in this filter to access the
servlet context within the doFilter() method.
34
FormChecker filter: init() and destroy() methods
package com.ibm.filters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FormChecker implements Filter {
FilterConfig config;
public void init(FilterConfig arg0)
throws ServletException {
config = arg0;
}
public void destroy() {
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-67
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: FormChecker: doFilter() Method (1 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-68 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-34. FormChecker filter: doFilter() method (1 of 2) RD7927.0
Notes:
The first part of the method deals with checking to see if any request parameter (as
identified by the init-param values of the filter) does not exist or has an empty value. If the
field is missing or empty, it is added to an array list object (fieldList), and a flag (doChain) is
set to false. The parameter __FORM_NAME is skipped because it holds the form name.
35
FormChecker filter: doFilter() method (1 of 2)
public void doFilter(ServletRequest arg0,
ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
boolean doChain = true;
ArrayList fieldList = new ArrayList();
Enumeration mandatory = config.getInitParameterNames();
if (mandatory != null) {
while (mandatory.hasMoreElements()) {
String parmName = (String) mandatory.nextElement();
if (!parmName.equals("__FORM_NAME")) {
String parmValue = arg0.getParameter(parmName);
String fieldName = "";
if (parmValue == null || parmValue.length() == 0) {
doChain = false;
fieldName = config.getInitParameter(parmName);
fieldList.add(fieldName);
}
}
}
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-69
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: FormChecker Filter: doFilter() Method (2 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-70 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-35. FormChecker filter: doFilter() method (2 of 2) RD7927.0
Notes:
This part of the code acts upon the decision made in the first part. If all of the mandatory
fields are filled in, then doChain is true, so the doFilter() method is invoked and the Prime
servlet is executed (along with any other filters further down the chain than FormChecker).
If doChain is false, the array list of field names that were missing or had empty values is
added as an attribute to the request, and control is forwarded to a JSP page named
BadForm.jsp. This page will display a response that notifies the user as to which fields
have missing values.
Note that this filter might also be used in testing to warn developers that they had left a
required field off of a page.
36
FormChecker filter: doFilter() method (2 of 2)
if (doChain) {
arg2.doFilter(arg0, arg1);
} else {
String formNameValue =
config.getInitParameter("__FORM_NAME");
String formName =
(formNameValue == null) ? "Form" : formNameValue;
arg0.setAttribute("formname", formName);
arg0.setAttribute("fieldlist", fieldList);
config.getServletContext().getRequestDispatcher
("/BadForm.jsp").forward(arg0, arg1);
}
}
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-71
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: FormChecker Filter: How It Works
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-72 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-36. FormChecker filter: How it works RD7927.0
Notes:
37
FormChecker filter: How it works
Mandatory field names are read from the init-param values of the
filter as an Enumeration
Each init-param is tested to see if the request parameter of that
name exists and is non-empty
If the parameter does not exist or is empty, then the field name
(value of the init-param) is added to a list and the doChain flag
is set to false (blocking the request)
If all mandatory fields are non-empty, doFilter() passes control to
the next filter on the chain, and ultimately to the Prime servlet
Otherwise, the chain is blocked
The array list of missing field names and the form name (value
of __FORM_NAME init-param) are put into request attributes
Control is forwarded to a JSP file to construct
an error page
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-73
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement The final example shows how a filter might change the response
from a filter. This requires the use of a ResponseWrapper object, which is introduced on
the next slide, before the example.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-74 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-37. Wrapping request and response objects RD7927.0
Notes:
The next example shows one way of using a custom response object in a filter.
38
Wrapping request and response objects
Filters may wrap the request and response objects to create
new custom request and response objects
The wrapped objects might:
Override existing methods
Create new methods
Custom request and response objects are typically created by
extending:
HttpServletRequestWrapper
HttpServletResponseWrapper
Subsequent methods in the filter chain have access to these
new custom objects created by wrapping
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-75
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Trailer Filter: Function Description
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-76 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-38. Trailer filter: Function description RD7927.0
Notes:
The filter appends the message as an HTML paragraph (the trailer) immediately before the
</BODY> tag of the response that was created by subsequent filters in the chain (including
the target Web resource). This filter assumes that the response is HTML.
In order for the filter to splice the trailer into the response created by subsequent filters and
the Web resource, the custom response object passed to them (using doFilter()) must
collect their responses into a String. The getWriter() method of the custom response object
is overridden so that a StringWriter is returned instead of a PrintWriter; this has the
desired effect of buffering the responses into a String when the filtered resources uses the
println() method of the returned writer to generate the response stream. Upon return from
doFilter(), the filter can now use the toString() method to extract the response generated
by the filtered resource as a string, splice in the trailer message, add </BODY> and
</HTML> tags to the string, and finally send that string back to the client.
39
Trailer filter: Function description
Appends a message to the end of the response object
The message is stored as a filter init-param
A custom response object is created:
Extends HttpServletResponseWrapper
Buffers response in a StringWriter
Overrides:
toString(): Extracts StringWriter buffer as a String
getWriter(): Returns PrintWriter based on the StringWriter
Subsequent filters use the custom getWriter() method
The custom response object is passed to the chain instead of
the original response object
After return from the chain, the response is
unwrapped, the message is added to it,
and both are written to the original
response object
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-77
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Trailer Filter: Deployment Descriptor
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-78 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-39. Trailer filter: Deployment descriptor RD7927.0
Notes:
Notice that the filter-mapping element uses the url-pattern element to define which Web
resource is to be filtered (that is, the end of the chain).
The result of the filter display Watch for our new Web Site coming soon! as a paragraph at
the end of the page that Welcome.jsp produces.
40
Trailer filter: Deployment descriptor
<filter>
<filter-name>WelcomeTrailer</filter-name>
<display-name>Welcome Trailer</display-name>
<filter-class>
com.ibm.filters.Trailer
</filter-class>
<init-param>
<param-name>msg</param-name>
<param-value>
Watch for our new Web Site coming soon!
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>WelcomeTrailer</filter-name>
<url-pattern>/Welcome.jsp</url-pattern>
</filter-mapping>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-79
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Trailer Filter: init() Method
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-80 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-40. Trailer filter: init() method RD7927.0
Notes:
The init() method copies the config to an instance variable and also gets the init-param
message and puts it in the msg class variable.
The destroy() method, which is empty, is not shown here.
41
Trailer filter: init() method
package ibm.com.filters;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class Trailer implements Filter {
private String msg = "";
private FilterConfig config;
public void init(FilterConfig arg0)
throws ServletException {
config = arg0;
msg = config.getInitParameter("msg");
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-81
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Trailer Filter: doFilter() Method
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-82 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-41. Trailer filter: doFilter() method RD7927.0
Notes:
The new response object (strResp) is created before the call to chain.doFilter() and
passed as one of its parameters. Essentially, strResp holds the responses of the
downstream filters in a string so that this filter can then extract and modify them to form the
final response to the client.
42
Trailer filter: doFilter() method
public void doFilter(ServletRequest arg0,
ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
StringResponse strResp = new
StringResponse((HttpServletResponse) arg1);
arg2.doFilter(arg0, strResp);
PrintWriter out = arg1.getWriter();
String responseString = strResp.toString();
int endBodyIndex = responseString.indexOf("</BODY>");
if (endBodyIndex > -1) {
StringBuffer finalResponse = new
StringBuffer(responseString.substring(0,
endBodyIndex - 1));
finalResponse.append("<P>");
finalResponse.append(msg);
finalResponse.append("</P></BODY></HTML>");
String finalResponseString = finalResponse.toString();
out.write(finalResponseString);
} else {
out.write(responseString);
}
out.close();
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-83
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Custom Response: StringResponse
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-84 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-42. Custom response: StringResponse RD7927.0
Notes:
This slide shows the implementation code for the custom response object, which extends
the HttpServletRespnseWrapper class. The toString() and getWriter() methods are
overridden from the base class.
43
Custom response: StringResponse
package ibm.com.sw284.filters;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class StringResponse extends
HttpServletResponseWrapper {
private StringWriter responseWriterBuffer;
public StringResponse(HttpServletResponse resp) {
super(resp);
responseWriterBuffer = new StringWriter();
}
public String toString() {
return responseWriterBuffer.toString();
}
public PrintWriter getWriter() {
return new PrintWriter(responseWriterBuffer);
}
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-85
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Trailer Filter: How It Works
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-86 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-43. Trailer filter: How it works RD7927.0
Notes:
Note that the code assumes the end body tag is exactly </BODY>. This code might be
improved by handling the lower and mixed case forms of this tag.
44
Trailer filter: How it works
New instance of custom response object (StringResponse) created
Wrapped response passed to next filter (Welcome.jsp) using
chain.doFilter()
The toString() method of the StringResponse object extracts the response
created by Welcome.jsp
The </BODY> tag is searched for in the extracted response
Assuming the </BODY> tag is found:
A substring of the response up to the </BODY> tag is created
The message is added to the substring
New </BODY> and </HTML> tags are added
The new response is sent to the PrintWriter of the original request
Otherwise, an unmodified response is sent to the PrintWriter
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-87
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Unit Summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-88 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-44. Checkpoint RD7927.0
Notes:
Write down your answers here:
45
Checkpoint
1. What interface is implemented to build a filter?
2. What object defines the sequence of filter execution?
3. How can a filter change the flow of processing to other filters?
4. What is the position of the user-requested Web resource on the filter
chain?
5. How many instances of a filter does the web container create?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-89
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-90 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-45. Checkpoint solutions RD7927.0
Notes:
46
Checkpoint solutions
1. What interface is implemented to build a filter?
The javax.servlet.Filter interface is implemented to build a filter.
2. What object defines the sequence of filter execution?
The FilterChain object defines the sequence of filter execution. The
container passes an object of this type to the first filter. The execution
is defined by the filter-mapping elements in the deployment descriptor.
The order of execution is determined by the order of matching filter-
mapping elements in the deployment descriptor.
3. How can a filter change the flow of processing to other filters?
A filter can control the flow of processing by not calling the
FilterChain.doFilter() method. In this case, it is responsible for
providing the response object.
4. What is the position of the user-requested Web resource on the filter
chain?
The requested Web resource is last on the filter chain.
5. How many instances of a filter does the web container create?
The container produces one instance of a filter for each filter element
defined in the deployment descriptor.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-91
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-92 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 24-46. Unit summary RD7927.0
Notes:
47
Having completed this unit, you should be able to:
Describe the processing flow for filters
List the Servlet API interfaces and support object used to
implement filters
Create a new filter using Rational Application Developer
Create deployment descriptor entries for a filter
Develop a basic filter using the appropriate interfaces
Develop a filter that blocks normal filter chain execution
Develop a filter using a wrapped custom response object
Having completed this unit, you should be able to:
Describe the processing flow for filters
List the Servlet API interfaces and support object used to
implement filters
Create a new filter using Rational Application Developer
Create deployment descriptor entries for a filter
Develop a basic filter using the appropriate interfaces
Develop a filter that blocks normal filter chain execution
Develop a filter using a wrapped custom response object
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 24. Servlet Filtering 24-93
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
24-94 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-1
V4.0
Uempty
Unit 25.Servlet Listeners
Estimated time
00:30
What this unit is about
This unit describes the Servlet Listener feature of the Servlet API,
Version 2.4.
What you should be able to do
After completing this unit, you should be able to:
Define Servlet Listeners and describe how they can be used in a
Web application
List typical uses of Servlet Listeners
Describe the major steps used to create Servlet Listeners
Name the six interfaces used to create Servlet Listeners and when
to use each interface
List the methods defined for each of the Servlet Listeners
interfaces and their use
Describe how to define a Servlet Listener to the Web application
State the rules for determining the order of execution of multiple
Listeners in a Web application
Describe the facilities of Application Developer used for
development of Servlet Listeners
How you will check your progress
Accountability:
Checkpoint
References
http://java.sun.com/j2ee/1.4/docs/api/index.html
Java2 Platform Enterprise Edition, v 1.4 API
Specification
http://www.jcp.org/aboutJava/communityprocess/final/jsr154/
JSR-000154 JavaTM Servlet 2.4 Specification
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Define Servlet Listeners and how they can be used in a Web
application
List typical uses of Servlet Listeners
Describe the major steps used to create a Servlet Listener
Name the six interfaces used to create Servlet Listeners and
when to use each interface
List the methods defined for each of the Servlet Listener
interfaces and their use
Describe how to define a Servlet Listener to the Web
application
State the rules for determining the order of execution of
multiple Listeners in a Web application
Describe the facilities of Application Developer used for the
development of Listeners
After completing this unit, you should be able to:
Define Servlet Listeners and how they can be used in a Web
application
List typical uses of Servlet Listeners
Describe the major steps used to create a Servlet Listener
Name the six interfaces used to create Servlet Listeners and
when to use each interface
List the methods defined for each of the Servlet Listener
interfaces and their use
Describe how to define a Servlet Listener to the Web
application
State the rules for determining the order of execution of
multiple Listeners in a Web application
Describe the facilities of Application Developer used for the
development of Listeners
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Basic Concepts of Servlet Event Listeners
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-2. Basic concepts of Servlet Event Listeners RD7927.0
Notes:
Servlet Listeners were introduced in Servlet 2.3 and extended in Servlet 2.4. They are
supported by Rational Application Developer.
The Servlet Specification also defines two more listeners that are less often used:
HttpSessionActivationListener listens for session activation and passivation.
HttpSessionBindingListener listens for objects being bound to or unbound from the
session.
These two listener types are not further discussed in this unit.
3
Basic concepts of Servlet Event Listeners
What is a Servlet Event Listener?
A class that can listen and react to certain types of events and state
changes in a Web application
Allows developers to:
Let Listener objects listen for Web module state changes:
ServletContext lifecycle: Creation and destruction
ServletContext attributes: Addition, replacement, and removal
HttpSession lifecycle: Creation and destruction
HttpSession attributes: Addition, replacement, and removal
ServletRequest lifecycle: Creation and destruction
ServletRequest attributes: Addition, replacement, and removal
Execute actions in response to the events
Advantages:
More control over interactions with application, session and request
objects
Centralized monitoring and response to events
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Examples of Servlet Listener Use
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-3. Examples of Servlet Listener use RD7927.0
Notes:
4
Examples of Servlet Listener use
Examples:
Monitor start and stop of Web modules to perform startup
and shutdown tasks
Add attributes to ServletContext or HttpSession objects
on creation
Monitor creation and destruction of sessions
Log important application events
Sample scenario:
When application starts, listener is notified and creates a
connection to the database. Connection is stored in servlet
context attribute
Servlets access the connection as needed from the servlet
context
When the Web application is shutdown, listener is notified
and closes database connection
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: How to Create a Servlet Listener
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-4. How to create a Servlet Listener RD7927.0
Notes:
The zero-argument constructor is provided so that the container (which handles the life
cycle of the listeners) can create instances as necessary. The zero-argument constructor
does not have to be provided explicitly, as the default constructor often suffices.
5
How to create a Servlet Listener
Create a class the implements at least one of the six listener
interfaces
ServletContextListener
ServletContextAttributesListener
HttpSessionListener
HttpSessionAttributesListener
ServletRequestListener
ServletRequestAttributesListener
Implement methods in the interface
Methods correspond to specific events
Code logic to respond to events
Create a public zero-argument constructor for the class
Add the listener to the Web Deployment Descriptor
A <listener> element defines the listener
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Selecting Servlet Listener Interfaces
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-5. Selecting Servlet Listener interfaces RD7927.0
Notes:
Each interface provides a method which the Listener developer can override to react to one
of the actions. When one of these actions occurs, the container invokes the method.
6
Selecting Servlet Listener interfaces
Select the listener interfaces to implement according to
the objects and actions to monitor
javax.servlet.
ServletRequestAttributesListener
Add attribute
Remove attribute
Replace attribute
ServletRequest
javax.servlet.
ServletRequestListener
Create
Destroy
ServletRequest
javax.servlet.http.
HttpSessionAttributesListener
Add attribute
Remove attribute
Replace attribute
HttpSession
javax.servlet.http.
HttpSessionListener
Create
Destroy
HttpSession
javax.servlet.
ServletContextAttributesListener
Add attribute
Remove attribute
Replace attribute
ServletContext
javax.servlet.
ServletContextListener
Create
Destroy
ServletContext
Interface Actions Object
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-11
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Selecting Methods for ServletContext Events
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-6. Selecting methods for ServletContext events RD7927.0
Notes:
Since you are implementing interfaces, you will need to provide an implementation for each
of the methods in the interface, even if the method has an empty body.
The methods have arguments that provide information about the events, as follows:
ServletContextEvent: Event class for notifications about changes to the servlet context
of an application
ServletContext getServletContext(): Returns the ServletContext that changed
ServletContextAttributeEvent: Event class for notifications about changes to the
attributes of a servlet context
java.lang.String getName(): Returns the name of the attribute that changed on the
ServletContext
java.lang.Object getValue(): Returns the value of the attribute that has been added,
removed, or replaced
7
Selecting methods for ServletContext events
To monitor lifecycle events (ServletContextListener interface)
use:
contextInitialized(ServletContextEvent e)
Called when Web application is ready to process requests
contextDestroyed(ServletContextEvent e)
Called when Web application is about to be shut down
To monitor attribute events
(ServletContextAttributesListener interface) use:
attributeAdded(ServletContextAttributeEvent e)
Called after an attribute is added to a ServletContext
attributeRemoved(ServletContextAttributeEvent e)
Called after an attribute is removed from a ServletContext
attributeReplaced(ServletContextAttributeEvent e)
Called after an attribute is replaced by another in a ServletContext
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-13
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Selecting Methods for HttpSession Events
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-7. Selecting methods for HttpSession events RD7927.0
Notes:
The methods have arguments that provide information about the events, as follows:
HttpSessionEvent: Event class for notifications about changes to the HTTP sessions
within a Web application
HttpSession getSession(): Returns the session that changed
HttpSessionBindingEvent: Event class for notifications about changes to attributes in
an HTTP Session
java.lang.String getName(): Returns the name of the attribute that changed on the
session
java.lang.Object getValue(): Returns the value of the attribute that has been added,
removed, or replaced
javax.servlet.http.HttpSession getSession(): Returns the session that changed
8
Selecting methods for HttpSession events
To monitor lifecycle events (HttpSessionListener interface),
use:
sessionCreated(HttpSessionEvent e)
Called when a session is created
sessionDestroyed(HttpSessionEvent e)
Called when a session is destroyed
To monitor attribute events (HttpSessionAttributesListener
interface), use:
attributeAdded(HttpSessionBindingEvent e)
Called after an attribute is added to a session
attributeRemoved(HttpSessionBindingEvent e)
Called after an attribute is removed from a session
attributeReplaced(HttpSessionBindingEvent e)
Called after an attribute is replaced by another in a session
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-15
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Selecting Methods for ServletRequest Events
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-8. Selecting methods for ServletRequest events RD7927.0
Notes:
Since you are implementing interfaces, you will need to provide an implementation for each
of the methods in the interface, even if the method has an empty body.
The methods have arguments that provide information about the events, as follows:
ServletRequestEvent: Event class for notifications about changes to the servlet
Request of an application
ServletRequest getServletRequest(): Returns the ServletRequest that changed
ServletContext getServletContextt(): Returns the current ServletContext
ServletRequestAttributeEvent: Event class for notifications about changes to the
attributes of a request
java.lang.String getName(): Returns the name of the attribute that changed on the
ServletContext
java.lang.Object getValue(): Returns the value of the attribute that has been added,
removed, or replaced
9
Selecting methods for ServletRequest events
To monitor lifecycle events (ServletRequestListener
interface) use:
requestInitialized(ServletRequestEvent e)
Called when the request is about to come into scope of the Web
application
requestDestroyed(ServletRequestEvent e)
Called when the request is about to go out of scope of the Web
application
To monitor attribute events
(ServletRequestAttributesListener interface) use:
attributeAdded(ServletRequestAttributeEvent e)
Called after an attribute is added to a ServletRequest
attributeRemoved(ServletRequestAttributeEvent e)
Called after an attribute is removed from a ServletRequest
attributeReplaced(ServletRequestAttributeEvent e)
Called after an attribute is replaced by another in a ServletRequest
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-17
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Defining Listeners to the Web Application
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-9. Defining Listeners to the Web application RD7927.0
Notes:
10
Defining Listeners to the Web application
Listeners are defined in the Web Deployment Descriptor
<listener> element defines a listener
More than one listener may be defined
Container executes listeners in order they appear in the deployment
descriptor file (web.xml)
Listener class file is placed in WEB-INF/classes or
packaged in JAR file in WEB-INF/lib
<listener>
<listener-class>
com.ibm.library.listeners.SessionCounter
</listener-class>
</listener>
<listener>
<listener-class>
com.ibm.library.listeners.LoggerListener
</listener-class>
</listener>
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-19
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Sample Servlet Listener Application (1 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 25-10. Sample Servlet Listener application (1 of 2) RD7927.0
Notes:
This application tracks the number of HTTP sessions established while the application is
running and prints out the maximum number of sessions that were encountered when the
server shuts down.
There are four getter and setter methods not shown. The number of sessions and the
maximum number of sessions are integers and are stored in the servlet context attributes
and the four getter and setter methods control access to these values. The counters need
to be managed this way because instance variables in Servlet Listeners behave just as
they do in servlets. The getter and setter for the number of sessions are
getCurrentSessions() and setCurrentSessions(). The getter and setter for the maximum
number of session are getMaxSessions() and setMaxSessions(). The code for these
methods is at the bottom of this note.
When the application starts, the contextIntialized() method is called by the container. This
method initializes the counters for the number of sessions and maximum sessions to zero
by using the setter methods for the counters. These setter methods store the Integer object
representation of the counts in servlet context attributes.
11
Sample Servlet Listener application (1 of 2)
public class SessionCounter implements ServletContextListener,
HttpSessionListener {
// Called when web app ready to process requests
// Initialize current session and max session counts to 0
public void contextInitialized(ServletContextEvent arg0) {
ServletContext sc = arg0.getServletContext();
setCurrentSessions(sc, 0);
setMaxSessions(sc, 0);
}
// Called when web application is about to be shutdown
// Print out max session count at the console
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Max sessions: " +
getMaxSessions(arg0.getServletContext()));
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-21
V4.0
Uempty
When the application shuts down, the contextDestroyed() method is called by the
container and prints out a message that includes the maximum number of sessions. It uses
the getter method to obtain the maximum number of sessions counter for a servlet context
attribute.
The code for handling the creating and destruction of the HTTP sessions is shown on the
next slide. These methods maintain the counts of the number of sessions and the
maximum number of sessions.
Here is the code for the getter and setter methods mentioned above:
private void setCurrentSessions(ServletContext sc, int currentSessions) {
sc.setAttribute("CURRENTSESSIONS", new Integer(currentSessions));
}
private void setMaxSessions(ServletContext sc, int maxSessions) {
sc.setAttribute("MAXSESSIONS", new Integer(maxSessions));
}
private int getMaxSessions(ServletContext sc) {
return ((Integer) sc.getAttribute("MAXSESSIONS")).intValue();
}
private int getCurrentSessions(ServletContext sc) {
return ((Integer) sc.getAttribute("CURRENTSESSIONS")).intValue();
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information arg0 is used as a parameter (rather than some more
informative name) because this is what the Rational Application Developer Servlet Listener
wizard generates.
Transition statement Next: Sample Servlet Listener Application (2 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-23
V4.0
Uempty
Figure 25-11. Sample Servlet Listener application (2 of 2) RD7927.0
Notes:
When a session is created, the sessionCreated() method is executed by the container.
The method uses the getter methods for the number of sessions and maximum session to
store these value in int variables. The number of sessions is incremented and compared to
the maximum sessions. The maximum sessions counter is updated if the current number of
sessions exceeds the current maximum sessions. The setter methods store the updated
counters back into the servlet context.
When a session is deleted, the sessionDestroyed() method is executed by the container.
This method gets the counter for the number of sessions (getCurrentSessions()),
decrements it, and stores it back in the servlet context with the setCurrentSessions()
method.
12
Sample Servlet Listener application (2 of 2)
// Called when a session is created
// Increment session count and compare to max sessions
public void sessionCreated(HttpSessionEvent arg0) {
ServletContext sc = arg0.getSession().getServletContext();
int currentSessions = getCurrentSessions(sc)+ 1;
int maxSessions = getMaxSessions(sc);
if (currentSessions > maxSessions) {
setMaxSessions(sc, currentSessions);
}
setCurrentSessions(sc, currentSessions);
}
// Called when a session is destroyed
// Decrement session count
public void sessionDestroyed(HttpSessionEvent arg0) {
ServletContext sc = arg0.getSession().getServletContext();
setCurrentSessions(sc, getCurrentSessions(sc) - 1 );
}
}
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Creating New Servlet Listeners with Wizards
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-25
V4.0
Uempty
Figure 25-12. Creating new Servlet Listeners with wizards (1 of 2) RD7927.0
Notes:
Application Developer has a wizard that will produce a class skeleton for a listener. On the
first page of the dialog you enter the display name and optional description
On the second page, enter the destination folder, Java package, and provide the name of
the class.
13
Creating new Servlet Listeners with wizards (1 of 2)
Application Developer has a Create Listener wizard
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-27
V4.0
Uempty
Figure 25-13. Creating new Servlet Listeners with wizards (2 of 2) RD7927.0
Notes:
The third page of the dialog allows you to select the interfaces that you use in the listener
class. The six standard listener interfaces are included by default. Remove the interfaces
that you do not want.
After clicking Finish, the file you created with the wizard will contain a class skeleton with
the class definition and all the methods defined for the interfaces that you selected. You
can now add the code to the methods to handle the events. The class is also listed in
web.xml.
14
Creating new Servlet Listeners with wizards (2 of 2)
Remove the interfaces you do not wish to implement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-29
V4.0
Uempty
Figure 25-14. Maintaining the Listener Definition RD7927.0
Notes:
15
Maintaining the Listener Definition
Application Developer lists Listeners in the Listener
area of the Variables tab of the Web Deployment
Descriptor
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Checkpoint
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-31
V4.0
Uempty
Figure 25-15. Checkpoint RD7927.0
Notes:
Write down your answers here:
16
Checkpoint
1. Define a Servlet Listener.
2. What are the lifecycle actions that can be monitored by a Servlet
Listener for the ServletContext object?
3. What are the attribute actions that can be monitored by a Servlet
Listener for a ServletContext object?
4. What are the lifecycle actions that can be monitored by a Servlet
Listener for the HttpSession object?
5. What are the attribute actions that can be monitored by a Servlet
Listener for a HttpSession object?
6. Name the six interfaces that can be implemented to construct a
Servlet Listener class.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-33
V4.0
Uempty
Figure 25-16. Checkpoint solutions RD7927.0
Notes:
17
Checkpoint solutions
1. Define a Servlet Listener.
A class that can listen and react to certain types of events and state
changes in a Web application.
2. What are the lifecycle actions that can be monitored by a Servlet
Listener for the ServletContext object?
Creation and destruction of the servlet context.
3. What are the attribute actions that can be monitored by a Servlet
Listener for a ServletContext object?
Removal, addition, and replacement of a servlet context attribute.
4. What are the lifecycle actions that can be monitored by a Servlet
Listener for the HttpSession object?
Creation and destruction of a HTTP session.
5. What are the attribute actions that can be monitored by a Servlet
Listener for a HttpSession object?
Removal, addition, and replacement of a session attribute.
6. Name the six interfaces that can be implemented to construct a
Servlet Listener class.
ServletRequestAttributeListener HttpSessionListener
ServletRequestListener ServletContextAttributesListener
HttpSessionAttributesListener ServletContextListener
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 25. Servlet Listeners 25-35
V4.0
Uempty
Figure 25-17. Unit summary RD7927.0
Notes:
18
Having completed this unit, you should be able to:
Define Servlet Listeners and how they can be used in a Web
application
List typical uses of Servlet Listeners
Describe the major steps used to create a Servlet Listener
Name the six interfaces used to create Servlet Listeners and
when to use each interface
List the methods defined for each of the Servlet Listener
interfaces and their use
Describe how to define a Servlet Listener to the Web
application
State the rules for determining the order of execution of
multiple Listeners in a Web application
Describe the facilities of Application Developer used for the
development of Listeners
Having completed this unit, you should be able to:
Define Servlet Listeners and how they can be used in a Web
application
List typical uses of Servlet Listeners
Describe the major steps used to create a Servlet Listener
Name the six interfaces used to create Servlet Listeners and
when to use each interface
List the methods defined for each of the Servlet Listener
interfaces and their use
Describe how to define a Servlet Listener to the Web
application
State the rules for determining the order of execution of
multiple Listeners in a Web application
Describe the facilities of Application Developer used for the
development of Listeners
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
25-36 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-1
V4.0
Uempty
Unit 26.Best Practices for Server-Side Application
Dev.
Estimated time
00:30
What this unit is about
This unit describes some of the practices that can be applied to the
design and development of world-class server-side application
systems.
What you should be able to do
After completing this unit, you should be able to identify the important
issues involved in server-side application development and testing:
Identify the important issues involved in server-side application
development and testing
Use layering in the design of a new enterprise application
List some of the benefits and disadvantages of layering
Describe the roles that J2EE elements usually play in a layered
architecture
Explain layered architecture and what each layer does
List servlet and JSP design considerations
Explain servlet and JSP patterns and guidelines
How you will check your progress
Accountability:
Checkpoint
Discussion
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Identify the important issues involved in server-side
application development and testing
Use layering in the design of a new enterprise application
List some of the benefits and disadvantages of layering
Describe the roles that J2EE elements usually play in a
layered architecture
Explain layered architecture and what each layer does
List servlet and JSP design considerations
Explain servlet and JSP patterns and guidelines
After completing this unit, you should be able to:
Identify the important issues involved in server-side
application development and testing
Use layering in the design of a new enterprise application
List some of the benefits and disadvantages of layering
Describe the roles that J2EE elements usually play in a
layered architecture
Explain layered architecture and what each layer does
List servlet and JSP design considerations
Explain servlet and JSP patterns and guidelines
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-2. The layering concept RD7927.0
Notes:
In thinking about the layering concept as an architectural pattern, you can consider the
forces:
You need a way of dividing work among team members so that they can work
concurrently and almost independently on the construction of an application
An architecture that is simple is easier to explain and to visualize. Simplicity makes it
easier to explain an application to new team members, and it makes the application
easier to extend or maintain
The layer idea addresses the way that an application is connected to things in its
environment
The layering concept is not a new one. The OSI Reference Model was developed by the
International Standards Organization in early 1980's. A simple introduction to the OSI
Reference Model can be found at http://www.webopedia.com/quick_ref/OSI_Layers.asp or
http://www2.rad.com/networks/1994/osi/layers.htm
3
The layering concept
High-level or
architectural pattern
Forces
Dividing work
Simplicity of
connection between
layers
External
connections
Layer or tier?
The terms are often
used
interchangeably
Tier may imply
physical separation
A
B
C
D
Higher
layer uses
services of
lower layer
Layer cake
C is hidden from A
D is hidden from A and B
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-5
V4.0
Uempty
Kyle Brown talks about layering as a pattern at
http://www.c2.com/cgi/wiki?FourLayerArchitecture
"When people discuss layering, there's often some confusion over the terms layer and tier.
Often the two are used as synonyms, but most people see tier as implying a physical
separation." [Fowler 02] p19.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-7
V4.0
Uempty
Figure 26-3. Advantages of layering RD7927.0
Notes:
4
Advantages of layering
Can see where each object fits into the Big Picture
Each layer can be understood as a coherent whole without
reference to other layers
Managing complexity through encapsulation
Information hiding
Layers can be replaced with alternative implementations
without changing the higher layers
Layers can be used to introduce standards
Layers can be reused in several applications
Layers can be tested as a unit independently of the
applications into which they are integrated
Better division of labor
Specialists in the technology used and the design of
particular layers
Each layer has its own operational responsibilities
Can avoid cascading changes
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-9
V4.0
Uempty
Figure 26-4. Disadvantages of layering RD7927.0
Notes:
Layers can be optimized if layer developers are able to maximize efficiency within their own
layer.
The ability to avoid cascading changes was listed, on the previous slide, as a benefit of
layering. What is going on here? Layering helps you avoid cascading changes when only
the implementation of underlying layers is modified. For example, if a database column is
renamed, only the data layer of the application needs to be changed. But consider the
classic situation in which the addition of a field to the UI forces the addition of a field to the
data layer and all layers in between. In such cases, layering gets in the way.
5
Disadvantages of layering
Cascading changes
Extra layers can adversely affect performance
More levels of indirection
Transforming one representation into another at each layer
boundary
Layers can also be used to perform optimization and caching
This can improve performance
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-11
V4.0
Uempty
Figure 26-5. Two-layer architecture RD7927.0
Notes:
6
Two-layer architecture
Also known as two-tier
architecture or client/server
architecture
Typically:
Client provides user interface
Server is a database
Characteristics:
Multiple applications share a
common database
All processing in the client
App 1
App 2
App 3
Database
Network
Client Server
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-13
V4.0
Uempty
Figure 26-6. Problems with two-layer architecture RD7927.0
Notes:
Stored procedures do not model the semantics of the enterprise particularly well; they are
normally not well supported by development tools; and they are difficult to debug.
7
Problems with two-layer architecture
Database structure can only partially model the semantics of
the enterprise
It is hard to represent complex business rules
Where to put shared processing and logic?
Putting it on the client can cause maintenance problems
Integrity control largely up to application programmers
This can also be controlled at the database level
Ramifications of changing database structure on which
multiple applications depend directly
Stored procedures offer some relief by abstracting access
to the database
Data may be spread across multiple databases
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details Students may argue that stored procedures are the solution to the problems of
database integrity control and database change control. They are partially right. But stored
procedures do not model the semantics of the enterprise particularly well; they are normally
not well supported by development tools; and they are difficult to debug.
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-15
V4.0
Uempty
Figure 26-7. Three-layer architecture RD7927.0
Notes:
This is the broad overview of a layered architecture.
Core J2EE Patterns divides the presentation layer into the Client and Web layers.
Marinescu further divides this layer into Presentation and Application:
Presentation layer: HTML, JSP, Swing, Flash, and so forth
Application layer: Session management (HTTPSession, for example), syntactic
validation, UI workflow.
The "glue"
Marinescu divides the business layer in two:
Services
- Business workflow
- Transaction control
- May support multiple Application layers
8
Three-layer architecture
The presentation layer deals with all
interaction between the user and the rest
of the application
The business layer encapsulates
application-specific business rules
It can also model complex structural
relationships and patterns
The data layer deals with communication
with other systems
For example, databases and other
enterprise information systems
Often an object-oriented model in
software, on top of a relational
database
Presentation layer
Business layer
Data layer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Domain
- Application-independent
Marinescu calls the data layer the Persistence layer, the J2EE Tutorial calls it the
Enterprise Information System (EIS) Tier.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-17
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-8. Layering in J2EE RD7927.0
Notes:
Roles given to J2EE components depend on approach.
For example:
JSP or servlet could implement business logic.
Session EJB could form part of data layer.
Heuristics for good assignment of roles is the subject matter of this course.
9
J2EE Server
Layering in J2EE
Web
container
Client
Data Business Presentation
DB
EJB
container
JSPs
Servlets
Session
EJBs
Entity
EJBs
Application
container
Browser
and applet
container
EIS
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-19
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-9. Sample implementation of patterns (1 of 2) RD7927.0
Notes:
10
Sample implementation of patterns (1 of 2)
What follows is a sample implementation of layering and
design patterns
The terms used in this sample application may vary from the
terms used in your organization or other pattern sites
The next slide contains a list of different pattern resources
that may use different terms
The goal of the sample implementation is to show you how
different patterns fit together
You are not expected to remember pattern names, or know
how to implement this solution
The goal of each slide is to provide a high level view of each
layer
The notes may go into more detail
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-21
V4.0
Uempty
Instructor notes:
Important
The sample application takes a whole course to explain. The intent of this overview is to get
the students interested in patterns and how they can fit together. Highlight the 3 layers, how
they fit together and that Transfer Objects flow in between the layers.
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-10. Sample implementation of patterns (2 of 2) RD7927.0
Notes:
11
Sample implementation of patterns (2 of 2)
References
The top Java EE best practices
http://www.ibm.com/developerworks/websphere/techjournal/0701_botz
um/0701_botzum.html
IBM Patterns for e-business
http://www.ibm.com/developerworks/patterns/
Java BluePrints
http://java.sun.com/blueprints/
Java EE Tutorials
http://java.sun.com/javaee/reference/tutorials
Core J2EE Patterns
http://www.corej2eepatterns.com
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-23
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-11. Sample layered application RD7927.0
Notes:
This sample application is from another IBM course that is dedicated to best practices.
Model-view-controller (MVC) design pattern demonstrates division of work in a vertical
fashion. Layering is a generalization of this concept. MVC is used in the sample
application, and additional layers are added to enhance division of work for the purpose of
greater flexibility in terms of designing and coding future changes. In addition, multiple
implementations of the model can be achieved without impacting controller and view
layers. Multiple types of views can make use of the model layer as well. An additional,
common extension to the MVC architecture is the explicit inclusion of the data mapping
layer which you have implemented using EJB and a simplified version using JDBC.
12
Sample layered application
Data layer
Business
layer
Presentation
layer
Model helpers
(Application business logic)
Thin client GUI (HTML, JSP)
Servlet, controller, state engine
Session faade
Action processor interface
Domain
(Data transfer
objects)
EJB mappers
Data server
EJB adapters JDBC adapters
JDBC mappers
Entity beans
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-25
V4.0
Uempty
Instructor notes:
Purpose
Details
Important
Do not spend much time on this slide as the following slides go into more detail. Also this is
only one way of implementing a layered architecture. Different variations can be used
instead.
Additional information
Transition statement Business tier layer
Data access layer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-12. Presentation layer (client) RD7927.0
Notes:
13
Presentation layer (client)
Thin-browser (HTML, JavaScript)
No applets
No application-specific installation on
client computer
Data layer
Business layer
Presentation layer
Servlet
Controller
State machine
Client
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-27
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-13. Presentation layer (servlet) RD7927.0
Notes:
14
Presentation layer (servlet)
Manages the requests for domain
state and behavior
Thin (minimum responsibilities)
Manages a static reference to the
controller (dispatcher)
Creates a HttpInteractionBean to
contain the HTTP request, response,
context
Forwards HttpInteractionBean to the
controller
Data layer
Business layer
Presentation layer
Servlet
Controller
State machine
Client
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-29
V4.0
Uempty
Instructor notes:
Purpose
Details The servlet is deliberately thin with the minimum responsibilities. These include
managing a static reference to the controller (dispatcher), creating a HttpInteractionBean to
contain the http interaction elements (request, response, context) and forwarding that bean
to the controller.
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-14. Presentation layer (controller) RD7927.0
Notes:
The responsibility of the controller is to execute the command against the correct state. It
interacts with the session to determine the state. Concrete implementations of the abstract
HttpController are responsible for the extraction of and invocation of the command. This
URI to "Action" mapping is a characteristic of the Apache Struts framework.
15
Presentation layer
Presentation layer (controller)
Created in Command Servlet
initialization
Controller class name provided as an
init parameter to the servlet
Executes commands against the
correct state
Interacts with the session to
determine the state
Data layer
Business layer
Servlet
Controller
State machine
Client
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-31
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-15. Presentation layer (state machine) RD7927.0
Notes:
The state machine approach means that there is one state object for each defined state in
the application, for example LoggedInState and UpdateUserInformationState. State objects
define all of the valid actions/commands which can be invoked for the sample application.
The State subclasses provide implementations which are appropriate for being in that
state. For example, you cannot perform many actions if you are in the LoggedOutState.
The state classes are responsible for interacting with the session, the HttpInteractionBean,
and providing state transitions for the application.
16
Presentation layer (state machine)
State objects for application states:
LoggedInState, StartState, and so
forth
Abstract class SampleState
One method per command
State subclasses override methods
to implement state-specific handling
of commands
Responsibilities
Extract incoming request
parameters
Invoke the model layer logic
Change to next state
Data layer
Business layer
Presentation layer
Servlet
Controller
State machine
Client
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-33
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-16. Business Layer (Action Processors) RD7927.0
Notes:
Action processors insulate the controller from the model implementation details and
provide the interface to the back-end server. All the state machine needs to know about
from a model perspective are the action processor interfaces, each of which define the
application interface of a set of related actions. There may be different implementations of
an ActionProcessor interface for different back-ends which reside in different packages, for
example, an EJB versus a non EJB back-end implementation.
17
Business Layer (Action Processors)
Not dependent on HTTP
Java interfaces for groups of actions
Example: CustomerActionProcessor
Insulates controller from the model
Implementations for EJB and JDBC
ActionProcessorFactory
Instantiates Action Processor
implementation objects
Checks properties file for EJB to
JavaBean switch
Caches Action Processor
singletons
Data layer
Business layer
Presentation layer
DTOs
Session
faades
Action
processors
Model
helpers
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-35
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-36 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-17. Business layer (data transfer objects) RD7927.0
Notes:
History of DTOs: Used to be known as Domain Objects. Now a misnomer.
DTOs are currently polluted with some business logic.
18
Business layer (data transfer objects)
Derived from an object model
Extend framework DomainObject
getMapper method
Serializable for transmission between
EJB server and servlets
Data layer
Presentation layer
Business layer
DTOs
Session
faades
Action
processors
Model
helpers
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-37
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-38 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-18. Business layer (session faades) RD7927.0
Notes:
EJBs consist of two major types - entity beans and session beans. Session beans are
typically coarse grained in that they can provide application business logic, and one call to
a session bean method may result in several actions being taken. These actions can reside
within a transaction, as the session bean can manage a transaction using the EJB
container provided by WebSphere. All transaction management for the EJBs is performed
by session beans. The sample application session beans are implemented using the
Facade pattern.
In a distributed architecture, the session beans are where the physical split would be made.
Session beans have a very similar interface to the ActionProcessors. The only interface
difference is that the Session beans methods must throw RemoteException.
In many EJB architectures, business logic is kept in the Session beans. In the architecture,
most of the business logic is moved to the Data Transfer Objects and Model Helper objects.
The primary responsibility of the Session object is to manage transactions and supply the
distributed interface for the model. They may have application business logic in how
back-end requests are grouped into transactions. The core enterprise business logic is
19
Business layer (session faades)
Purpose
Transaction management
Remoteability
Session faade pattern
Called by ActionProcessor
implementations
Similar methods to ActionProcessors
Very little business logic (in model
helpers instead)
Data layer
Presentation layer
Business layer
DTOs
Session
faades
Action
processors
Model
helpers
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-39
V4.0
Uempty
being kept independent of the persistence framework (EJBs, JDBC) and of the application
transactions (session beans).
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-40 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-41
V4.0
Uempty
Figure 26-19. Business layer (model helpers) RD7927.0
Notes:
Model helpers encapsulate the application specific business logic. The model helpers are
Java objects, not EJBs. This factoring is done for the purpose of flexibility in design.
In particular, application logic which may be employed within multiple units of work can be
reused without incurring the overhead of EJB to EJB calls. Further, since most of this logic
is independent of EJB technology, they can be reused in non-EJB based implementations.
When called by session beans, they participate in the EJB transaction and security
contexts. Model helpers employ domain objects and mappers to do their job.
20
Business layer (model helpers)
Encapsulate the application-specific
business logic
Java objects, not EJBs
Can be reused in non-EJB based
implementations
Can participate in EJB transaction
and security
Use DTOs and mappers
Data layer
Presentation layer
Business layer
DTOs
Session
faades
Action
processors
Model
helpers
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-42 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-43
V4.0
Uempty
Figure 26-20. Data layer (mappers) RD7927.0
Notes:
The role of mappers is to move data from domain objects to persistent data sources and
vice versa. The sample application allows for different mapping technologies, specifically
JDBC and EJB. Mappers are used by the model helpers to move the data to and from the
persistent layer.
21
Data layer (mappers)
Move data from DTOs to persistent
store and vice versa
Used by model helpers
Pluggable EJB and JDBC versions
Extend abstract EJBMapper or
JDBCMapper
MapperFactory
Instantiates appropriate mapper
Checks properties file for EJB to
JDBC switch
Data layer
Business layer
Mappers
Entity EJBs
Storage
Presentation layer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-44 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-45
V4.0
Uempty
Figure 26-21. Data layer (entity EJBs) RD7927.0
Notes:
22
Data layer (entity EJBs)
Manage the interface to the relational
database
Container-managed persistence
(CMP)
Business layer
Presentation layer
Data layer
Mappers
Entity EJBs
Storage
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-46 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-47
V4.0
Uempty
Figure 26-22. Decoupling the layers RD7927.0
Notes:
To illustrate the decoupling between the Business layer and the Data layer, consider the
need to replace an XML file with a relational database. Perhaps the application has
become more popular and needs the kind of heavy-duty backup, indexing and integrity
controls that a relational database can provide. Ideally you would like to make this change
without making massive changes to the Business layer.
23
Decoupling the layers
Logical separation
The three layers need not
be separate projects,
packages or even classes
Preserve ability to substitute
different lower layers
Business layer - does not know
about formatting of data for
display, interpreting requests from
UI, the database schema or the
type of data store
Presentation layer - does not know
what the application is about
Data layer - does not know how the
data is used
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-48 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details Discuss with the students what it would mean for the Business layer to be
decoupled from an HTTP-based Presentation layer. Consider:
Managing HTTP session state
Interpreting HTTP requests
Building HTTP responses
Handling double-keying of buttons
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-49
V4.0
Uempty
Figure 26-23. Accessing the data layer directly RD7927.0
Notes:
"Sometimes the layers are arranged so that the domain layer completely hides the data
source from the presentation. More often, however, the presentation accesses the data
store directly. While this is less pure, it tends to work better in practice. The presentation
may interpret a command from the user, use the data source to pull the relevant data out of
the database, and then let the domain logic manipulate that data before presenting it on the
glass." [Fowler 02] p20.
The classic example of bypassing layers for performance reasons is the direct use by
Session EJBs of JDBC to return read-only lists of things.
For a justification of judicious breaking of the rules, refer to [Marinescu 02] p130.
You do not have to have all the layers but.be careful. If possible avoid this quick and
dirty approach except for very simple applications. Complex extensions to the prototype
should be refactored to include a properly layered approach.
24
Accessing the data layer directly
Sometimes it may be desirable to go straight from the presentation layer
to the data layer
In this case, the presentation layer bypasses the business layer
Breaking the decoupling rule and removes many of the advantages
of layering
There may be good reasons for doing this
Performance
Simpler for trivial domain models
Quick prototypes
Must be done judiciously
How might this work?
The presentation layer interprets a command from user, uses the
data layer to pull data from database, uses the business layer to
manipulate data and presents the data on screen
Never let the business layer or the data layer be dependent on the
presentation layer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-50 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-51
V4.0
Uempty
Figure 26-24. Physical layering RD7927.0
Notes:
Splitting business logic between the client and the server: "The trick then is to isolate this
piece of logic in a self-contained module that is not dependent on any other part of the
system." [Fowler 02] p24.
Avoiding separate processes
Here are some thoughts about the decision between using local and remote EJBs. As you
will see, much of this thinking is based on [Fowler 02].
First, a position in regard to EJBs:
Entity EJBs are best accessed using local interfaces. Client layers typically access
entity EJBs through session EJBs, rather than directly. The trend is now to define
fine-grained interfaces to entity EJBs, which are deployed in the same container as the
session EJBs through which they are accessed.
Session EJBs typically have course-grained interfaces and are therefore better suited
to remote interfaces. But the choice of interface type is not as straight-forward as one
might think. The best approach is to define local interfaces for session EJBs and define
25
Physical layering
Where should you put business logic?
On the client for responsiveness or disconnected use
On the server for ease of control, updatability and
maintainability
Split between the client and the server, if you can separate
the logic to avoid getting the worst of both worlds
Avoid separate processes, which necessitate remote calls
Pass-by-value semantics
More complexity
Performance degradation
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-52 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
remote interfaces for them, or remote facades for them, only when the need arises to
access them remotely.
Here is the rationale for defining local interfaces for session EJBs by default:
Remote interfaces are slower to access. To minimize the number of calls to remote
interfaces, one typically defines the interface in terms of data transfer objects. So one
ends up with another set of classes to maintain and a interface to the session EJB layer
that is awkward to maintain.
Martin Fowler defines the First Law of Distributed Object Design thus: "Don't distribute
your objects." He recommends that you "fight like a cornered rat to eliminate as many of
[the remote interfaces] as you can", creating them only where you absolutely need to
deploy components in separate processes. He says, "... there may be some genuine
reason that you have to split your application server software. You should sell any
grandparent you can get your hands-on to avoid this."
Fowler says, "All things being equal it's best to run the Web and application servers in a
single process" unless you cannot do so because, for example, you are using Web
servers and application servers from different vendors. Most enterprises adopt this
approach.
In his discussion of the Service Layer pattern, Fowler talks more specifically about the
distribution of Service Layer objects (session EJBs in the J2EE world). After
acknowledging that Service Layer methods are more suited to remote invocation, he
says, "However, remote invocation comes at the cost of extra work to make your
Service Layer method signatures deal in Data Transfer Objects (401). Don't
underestimate the cost of this work, especially if you have a complex Domain Model
(116) and rich editing UIs for complex update use cases! It's significant, and it's painful -
perhaps second only to the cost and pain of object-relational mapping...Our advice is to
start with a locally invocable Service Layer whose method signatures deal in domain
objects. Add remoteability when you need it (if ever) by putting Remote Facades (388)
on your Service Layer or having your Service Layer objects implement remote
interfaces. If your application has a Web-based UI or a Web services-based integration
gateway, there's no law that says your business logic has to run in a separate process
from your server pages and Web services. In fact, you can save yourself some
development effort and runtime response time, without sacrificing scalability, by starting
out with a collocated approach." In regard to the Java implementation of a Service
Layer, Fowler says, "My preferred way of applying a Service Layer in J2EE is with EJB
2.0 stateless session beans, using local interfaces, and the operation script approach,
delegating to POJO domain object classes...Also, with the local interfaces introduced in
EJB 2.0, a Service Layer can exploit the valuable transaction services while avoiding
the thorny object distribution issues."
The XP principle of doing the simplest thing first applies here. If it is relatively easy to
add it laterand, in the case of remoteability of session EJB interfaces, it is. Avoid
writing now that thing that you may possibly need in the future.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-53
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-54 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-25. Servlet considerations RD7927.0
Notes:
Security: If the application requires different security behavior for different requests, then
this will have to be coded in each servlet.
Testability: Easier to test, and coverage is better when using one servlet for each request.
When using only one servlet for the entire application, you will need to use introspection to
find the associated action for each request, thus making testing more difficult.
26
Servlet considerations
There are many issues surrounding whether having one
servlet per request is the best technique:
Administration
The more servlets there are, the more there are to register and
configure
Security
Global or local security behavior
Testability
Easier with one servlet per request
Profiling
Easier to track performance and usage with one servlet per request
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-55
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-56 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-26. JSP design considerations RD7927.0
Notes:
The indirect model is referring to the MVC design pattern.
There can be multiple JSPs, each designed to support one of the possible outcomes of the
request of a client. Based on the results of the business logic, the controller decides which
JSP to forward to, and the appropriate response is displayed.
JavaServer Pages are recommended to be used for presentation only. The JavaBeans
provide the dynamic data, which can be used to populate the resulting dynamic Web page.
Scriptless JSP pages should be the goal.
27
JSP design considerations
Use the indirect model programming model
JSP is called indirectly, through a controller (servlet)
Sole purpose is to provide a response to the client
No control behavior within the JSP
Minimize the amount of Java code in the JSP
Just use the JSP for display purposes
Can be easily generated and viewed by JSP-aware HTML
page editors
Allows separation of model and view
Allows separation of development roles
Use custom tags
Put Java code in beans and call them with the <useBean>
tag
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-57
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-58 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-27. Other JSP guidelines RD7927.0
Notes:
28
Other JSP guidelines
Set session page directive attribute to false if session support
not required
Use the type and class attributes of the use:Bean tag correctly
The type attribute throws InstantiationException if object
not in scope
The class attribute creates object if not in scope
Consider guarding JSPs by placing them in the WEB-INF
directory
Avoid hardcoding the context path in a URL
Use contextPath property of HttpServletRequest
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-59
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-60 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-28. Synchronizer token: Problem RD7927.0
Notes:
29
Synchronizer token: Problem
Users can accidentally send
duplicate requests to the server
Example:
The user completes a form to
request an account transfer
The servlet is invoked and the
new balance is displayed
The user goes on to perform
another action in the web
application (Another Page)
The user clicks the Back button
on the browser
The browser displays a dialog
indicating data unavailable and
asking the user whether the
form data should be re-posted
If the user elects to re-post, the
funds will be transferred again
Input
transfer
information
Input
transfer
information
Current
balance
Current
balance
AcctTransfer
servlet
AcctTransfer
servlet
Back
Another
page
Another
page
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-61
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-62 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-29. Synchronizer token: Solution (1 of 2) RD7927.0
Notes:
30
Synchronizer token: Solution (1 of 2)
Synchronizer token pattern
Use a token to monitor and control the request flow and client
access to certain resources
The token is generated on the server and communicated back
to the client
This avoids duplicate requests and prevents clients accessing
certain views out of order by returning to previously
bookmarked pages
Client
Token
Controller
User
session
Token
Request
Token
Check client token
matches current
token in session
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-63
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-64 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-30. Synchronizer token: Solution (2 of 2) RD7927.0
Notes:
31
Synchronizer token: Solution (2 of 2)
Compare with
previous user token
from session
Compare with
previous user token
from session
Generate and
store new token
Generate and
store new token
Send response
Send response
Get client token
from request
Get client token
from request
Client
Client
Send error
response
Send error
response
Tokens match Tokens do not match
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-65
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-66 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-31. Checkpoint RD7927.0
Notes:
Write down your answers here:
32
Checkpoint
1. Why is it important to design a layered architecture?
2. What are some JSP design considerations?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-67
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-68 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-32. Checkpoint solutions RD7927.0
Notes:
33
Checkpoint solutions
1. Why is it important to design a layered architecture?
The primary design idea is to decouple the domain from
presentation and data source requirements. This layering
allows reuse of the domain objects across applications.
Developers need to design up front how each layer
communicates with the adjoining layer. This allows for
simultaneous development at each layer and distribution of
labor.
2. What are some JSP design considerations?
Use the Indirect Model programming model. The JSP is
called indirectly, through a controller (servlet). The sole
purpose of the JSP is to provide a response to the client.
There should be no control behavior within the JSP, and you
should minimize the amount of Java code in the JSP.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-69
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-70 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 26-33. Unit summary RD7927.0
Notes:
34
Having completed this unit, you should be able to:
Identify the important issues involved in server-side
application development and testing
Use layering in the design of a new enterprise application
List some of the benefits and disadvantages of layering
Describe the roles that J2EE elements usually play in a
layered architecture
Explain layered architecture and what each layer does
List servlet and JSP design considerations
Explain servlet and JSP patterns and guidelines
Having completed this unit, you should be able to:
Identify the important issues involved in server-side
application development and testing
Use layering in the design of a new enterprise application
List some of the benefits and disadvantages of layering
Describe the roles that J2EE elements usually play in a
layered architecture
Explain layered architecture and what each layer does
List servlet and JSP design considerations
Explain servlet and JSP patterns and guidelines
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 26. Best Practices for Server-Side Application Dev. 26-71
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
26-72 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-1
V4.0
Uempty
Unit 27.J2EE Packaging and Deployment
Estimated time
00:15
What this unit is about
This unit describes how enterprise applications are packaged
according to the J2EE specification.
What you should be able to do
After completing this unit, you should be able to:
Understand the relationship between components, modules, and
enterprise applications
State the containment hierarchy for J2EE packaging
Understand the purpose of each type of deployment descriptor
How you will check your progress
Accountability:
Checkpoint
Discussion
References
http://java.sun.com/j2ee/j2ee-1_4-fr-spec.pdf
Java 2 Platform Enterprise Edition Specification, v1.4
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Understand the relationship between components, modules
and enterprise applications
State the containment hierarchy for J2EE packaging
Understand what each type of deployment descriptor is used
for
After completing this unit, you should be able to:
Understand the relationship between components, modules
and enterprise applications
State the containment hierarchy for J2EE packaging
Understand what each type of deployment descriptor is used
for
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: J2EE Packaging
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-2. J2EE packaging RD7927.0
Notes:
3
J2EE packaging
The J2EE specification defines standard archive formats for all
J2EE components
EJB module
Packaged in a Java archive (.jar) file
Web module
Packaged in a Web archive (.war) file
Application client module
Packaged in a Java archive (.jar) file
Resource adapter module
Packaged in a resource adapter archive (.rar) file
Enterprise application
Packaged in an enterprise archive (.ear) file
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: J2EE Packaging - Containment Hierarchy
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-3. J2EE packaging Containment hierarchy RD7927.0
Notes:
Deployment descriptors are identified for each archive type with square-cornered
rectangles in this diagram. The resources packaged in each archive type are identified by
oval shapes in this diagram.
Each of the nodes of the hierarchy is described in the following slides.
4
web resource
JSP
Servlet
client1.jar
web1.war
res1.rar
EJB
client class
native library
adapter jar
ejb1.jar
J2EE packaging Containment hierarchy
app1.ear
ejb-jar.xml
application-client.xml
web.xml
Web resource
JSP
Servlet
ejb1.jar
client1.jar
web1.war
res1.rar
ra.xml
EJB
Client class
Native library
Adapter jar
application.xml
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: EJB Module
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-4. EJB module RD7927.0
Notes:
5
EJB module
An EJB module is contained in an EJB jar file
Several beans may be packaged within a single EJB jar file
The EJB JAR contains all the classes required for each EJB
The enterprise bean class
The enterprise bean home and component interfaces
The primary key class if the bean is an entity bean
The deployment descriptor (ejb-jar.xml) contains:
EJB structural information
Defining the class names, external dependencies, persistent fields and
relationships (for CMP beans)
Application assembly information describing how the EJBs
fit into a wider application
Security information and transaction attribute
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Web Module
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-5. Web module RD7927.0
Notes:
6
Web module
Web modules (also known as Web applications) are contained
in a Web archive (.WAR) file
A WAR file will normally contain several Servlets, JavaServer
Pages and other Web resources
For example, a Web application may contain HTML files,
graphics files, audio files and movies
The deployment descriptor (web.xml) contains configuration
information for resources contained in the WAR file
For example, initialization parameters, session
management configuration, servlet declarations and
mappings, filter definitions, welcome file list, and error
pages
Security information, tag libraries, and JNDI configuration
may also be provided
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-11
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Application Client Module
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-6. Application client module RD7927.0
Notes:
7
Application client module
Application clients are contained in jar file
An application client JAR file contains all the classes required
for the client to function
The deployment descriptor (application-client.xml)
contains configuration information for the client
The enterprise beans and external resources referenced by
the application client
The mechanism for deployment and installation of the
application client is not specified in the J2EE specification
J2EE product providers may provide an application launcher
that integrates with the native operating system of the
application client
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-13
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement Next: Resource Adapter Module
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-7. Resource adapter module RD7927.0
Notes:
8
Resource adapter module
Resource adapters are contained in a resource adapter
archive (.RAR) file
A resource adapter archive RAR file contains:
Java code for the resource adapter
Utility Java classes for the resource adapter
Platform-dependent native libraries required by the
resource adapter
Help files and documentation
The deployment descriptor (ra.xml) contains:
General information on the adapter
The class names of the connection factory and
implementation class
Transaction and security information
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-15
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information RARs are used with the Java Connector Architecture to
describe communication with an Enterprise Information System.
Transition statement Next: Enterprise Application
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-8. Enterprise application RD7927.0
Notes:
9
Enterprise application
Enterprise applications are contained in an enterprise archive
(.ear) file
An enterprise archive file contains one or more J2EE modules
EJB JARs, WARs, application client JARs and RARs
The enterprise application deployment descriptor
(application.xml) contains:
Details of all the modules packages in the EAR file
Definitions of security roles for the enterprise application
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-17
V4.0
Uempty
Instructor notes:
Purpose
Details
How are EJB modules packaged?
EJBs are packaged in EJB JAR files.
What is packaged in a WAR file?
Servlets, JSP Taglib Descriptor files, HTML files, JSP files, image and audio files. In
addition, the WAR contains the web.xml deployment descriptor file.
How are application client modules packaged?
Application clients are packaged in JAR files.
What is packaged in an EAR file?
Each of the module JAR and WAR files, any dependent JAR or resource files needed
by the application components, and the application.xml file. Extension and binding
(vendor specific) files are also included in the EAR file.
Why are there IBM bindings?
Bindings map the application to a particular deployment configuration. A particular
deployment configuration is vendor specific.
What is the AST?
The Application Server Toolkit (AST) is a tool for creating and modifying application
modules (JAR, WAR, and EAR files).
Additional information
Transition statement Next: Checkpoint
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-9. Checkpoint RD7927.0
Notes:
Write down your answers here:
10
Checkpoint
1. What is an EAR?
2. What are the four types of modules contained in an EAR?
3. What are the three types of archives contained in an EAR?
4. Which archive type contains servlets and JSP pages?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-19
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-10. Checkpoint solutions RD7927.0
Notes:
11
Checkpoint solutions
1. What is an EAR?
An enterprise archive
2. What are the four types of modules contained in an EAR?
EJB
Web
Resource adapter
Client application
3. What are the three types of archives contained in an EAR?
WAR (Web archive)
RAR (Resource archive)
JAR (Java archive)
4. Which archive type contains servlets and JSP pages?
WAR
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-21
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 27-11. Unit summary RD7927.0
Notes:
12
Having completed this unit, you should be able to:
Understand the relationship between components, modules
and enterprise applications
State the containment hierarchy for J2EE packaging
Understand what each type of deployment descriptor is used
for
Having completed this unit, you should be able to:
Understand the relationship between components, modules
and enterprise applications
State the containment hierarchy for J2EE packaging
Understand what each type of deployment descriptor is used
for
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 27. J2EE Packaging and Deployment 27-23
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
27-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-1
V4.0
Uempty
Unit 28.Installing an Application in WebSphere
Application Server V6.1
Estimated time
00:30
What this unit is about
This unit describes the tools used to install applications into
WebSphere Application Server, Version 6.0.
What you should be able to do
Review J2EE application packaging.
After completing this unit, you should be able to:
- Use the browser-based Administration Console
- Examine the ways that an enterprise application can be
installed and modified
- Configure the Application Server and J2EE Resources
How you will check your progress
Accountability:
Lab exercise
References
http://publib.boulder.ibm.com/infocenter/ws60help/index.jsp
WebSphere Application Server Version 6.0
Information Center
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 28-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Appreciate the overall use of the Administrative Console
Understand the configuration options available
Install an application
Modify existing installed applications
Configure J2EE resources
Save master configuration files
After completing this unit, you should be able to:
Appreciate the overall use of the Administrative Console
Understand the configuration options available
Install an application
Modify existing installed applications
Configure J2EE resources
Save master configuration files
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 28-2. WebSphere Administration Console RD7927.0
Notes:
3
WebSphere Administration Console
The Administration Console is browser-based
It can be used to display configuration information from the
XML configuration file
The server configuration can be modified
Applications can be controlled
Installed, uninstalled, started, stopped
Current state can be displayed
Application and module names and configuration can be viewed
It will also display deployment descriptors
Application
EJB modules
Web modules
Application client modules
It will allow you to edit some features
EJB module bindings
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 28-3. Administrative Console overview RD7927.0
Notes:
Access the console through URL http://localhost:9060/ibm/console/. You will be asked
to supply a User ID for tracking purposes, after which you can log in. The User ID does not
require a password, and does not need to be a User ID of a user in the local user registry. It
is only used to track user-specific changes to configuration data. Once you log in, you can
see the screen displayed above. In this case, the user logged in with a User ID of student.
4
Enter http://localhost:9060/ibm/console/
Administrative Console overview
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 28-4. Administrative Console navigation tree RD7927.0
Notes:
5
Administrative Console navigation tree
Choose an action:
Help with activities
Administer application and Web
servers
Administer and install
applications
Administer resource providers
(JDBC, JMS)
Enable and configure security
Configure virtual hosts,
environment variables
Administer the Administration
Console
Administer Users and Groups
Configure Performance
Monitoring Infrastructure
Configure Logs and Tracing
Configure SOA elements
Configure UDDI nodes
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 28-5. Applications: Console options RD7927.0
Notes:
To manage an installed J2EE enterprise application, enable the Select check box beside
the application name in the list and click a button:
Start
Attempts to run the application. After the application starts up successfully, the state of the
application changes to Started if the application starts up on all deployment targets,
otherwise the state changes to Partial Started.
Stop
Attempts to stop the processing of the application. After the application stops successfully,
the state of the application changes to Stopped if the application stops on all deployment
targets, otherwise the state changes to Partial Stopped.
Install
Opens a wizard that helps you deploy an application or a module such as a .jar, .war or
.rar file onto a server or a cluster.
6
Applications: Console options
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-11
V4.0
Uempty
Uninstall
Deletes the application from the WebSphere Application Server configuration repository
and deletes the application binaries from the file system of all nodes where the application
modules are installed after the configuration is saved and synchronized with the nodes.
Update
Opens a wizard that helps you update application files deployed on a server. You can
update the full application, a single module, a single file, or part of the application. If a new
file or module has the same name as a file or module already existing on the server, the
new file or module replaces the existing file or module. If the new file or module does not
exist on the server, it is added to the deployed application.
Rollout Update
Sequentially updates an application installed on multiple cluster members across a cluster.
After you update the files or configuration of an application, click Rollout Update to install
the updated files or configuration of the application on all cluster members of a cluster on
which the application is installed.
Remove File
Deletes a file from the WebSphere Application Server configuration repository and from the
file system of all nodes where the file is installed. If the application or module is deployed
on a cluster, after removing a file, click Rollout Update to roll out the changes across the
entire cluster.
Export
Accesses the Export Application EAR files page, which you use to export an enterprise
application to an EAR file at a location of your choice. Use the Export action to back up a
deployed application and to preserve its binding information.
Export DDL
Accesses the Export Application DDL files page, which you use to export DDL files
(Table.ddl) in the EJB modules of an enterprise application to a location of your choice.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-13
V4.0
Uempty
Figure 28-6. Applications: Installation (1 of 2) RD7927.0
Notes:
7
Applications: Installation (1 of 2)
Specify the application (EAR file) or stand-alone module (JAR or
WAR file) to install
If installing a Web module, specify the context root
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-15
V4.0
Uempty
Figure 28-7. Applications: Installation (2 of 2) RD7927.0
Notes:
8
Applications: Installation (2 of 2)
Remaining steps involve
Selecting installation options
Mapping modules to servers
Mapping virtual hosts for Web
modules
Once the application has been
installed, the master configuration
must be saved
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-17
V4.0
Uempty
Figure 28-8. Applications: Modification RD7927.0
Notes:
9
Applications: Modification
The Administration Console allows
limited configuration
Changes made through the
Administration Console wont be
reflected in the original EAR file
Application Developer or the
WebSphere Application Server
Toolkit can be used to modify
the original deployment
descriptors
Changes imply reinstalling the
application after modification
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-19
V4.0
Uempty
Figure 28-9. Servers: Configuration (1 of 2) RD7927.0
Notes:
10
Servers: Configuration (1 of 2)
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-21
V4.0
Uempty
Figure 28-10. Servers: Configuration (2 of 2) RD7927.0
Notes:
11
Servers: Configuration (2 of 2)
Basic settings are shown at the top of the form
The Runtime tab allows extensive configuration, including
logging, tracing and the transaction service
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-23
V4.0
Uempty
Figure 28-11. Resources: Configuration RD7927.0
Notes:
12
Resources: Configuration
JMS Providers
WebSphere MQ or others
JDBC Providers and data sources
Resource Adapters
Describe JCA access to
Enterprise Information Systems
Asynchronous Bean Control
Timers and work managers
Schedulers
Cache Management
Mail Providers
URL Providers
Allow URLs to be looked up
using JNDI
Resource Environment Providers
Allow resources to be located
using JNDI with logical names
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-25
V4.0
Uempty
Figure 28-12. Resources: JDBC DataSources RD7927.0
Notes:
13
Resources: JDBC DataSources
In addition to basic properties, connection pool options can be
set using the form
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-27
V4.0
Uempty
Figure 28-13. Resources: JMS connections RD7927.0
Notes:
14
Resources: JMS connections
Access to JMS resources can be configured through the
Admin Console
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-29
V4.0
Uempty
Figure 28-14. Saving master configuration RD7927.0
Notes:
15
Saving master configuration
Changes to the configuration must be saved
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-31
V4.0
Uempty
Figure 28-15. Checkpoint RD7927.0
Notes:
Write down your answers here:
16
Checkpoint
1. Can the Administration Console manage Web servers?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-33
V4.0
Uempty
Figure 28-16. Checkpoint solutions RD7927.0
Notes:
17
Checkpoint solutions
1. Can the Administration Console manage Web servers?
Yes, it can manage Web servers.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 28. Installing an Application in WebSphere Application Server 28-35
V4.0
Uempty
Figure 28-17. Unit summary RD7927.0
Notes:
18
Having completed this unit, you should be able to:
Appreciate the overall use of the Administrative Console
Understand the configuration options available
Install an application
Modify existing installed applications
Configure J2EE resources
Save master configuration files
Having completed this unit, you should be able to:
Appreciate the overall use of the Administrative Console
Understand the configuration options available
Install an application
Modify existing installed applications
Configure J2EE resources
Save master configuration files
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
28-36 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-1
V4.0
Uempty
Unit 29.Web Application Security
Estimated time
00:30
What this unit is about
This unit describes J2EE security support and configuration in
Rational Application Developer
What you should be able to do
After completing this unit, you should be able to:
Apply role-based security to a Web application
Gather roles in the application deployment descriptor
Configure a Web application authentication method
Set security role references for servlets
Configure security in the test environment

How you will check your progress
Accountability:
Checkpoint
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-1. Unit objectives RD7927.0
Notes:
2
After completing this unit, you should be able to:
Apply role-based security to a Web application
Gather roles in the application deployment descriptor
Configure a Web application authentication method
Set security role references for servlets
Configure security in the test environment
After completing this unit, you should be able to:
Apply role-based security to a Web application
Gather roles in the application deployment descriptor
Configure a Web application authentication method
Set security role references for servlets
Configure security in the test environment
Unit objectives
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-2. Role-based security RD7927.0
Notes:
The sample bank application defines two roles: an administrator role and a customer role.
While administrators can open accounts and check individual account balances, customers
can only check on their own account balance. Notice that this scheme does not tie access
to users; new customers can join the system and access the banking application without
changing the application code.
3
Role-based security
J2EE security uses roles to determine categories of users that
can access a particular enterprise application
Abstract group mapped to a set of security identities during
deployment.
Groups are similar to roles but apply to all enterprise
projects in the application server.
/accountInfo.jsp
/openAccount.jsp
Web application
Role = Administrator
Role = Customer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-3. Define security roles for Web applications RD7927.0
Notes:
A security role entry in the Web Deployment Descriptor editor represents the
<security-role> tag in the web.xml file. This tag only defines an abstract user role in the
Web application. You must create a security role reference to tie this user category to a
Web resource, such as a servlet or JSP.
4
Define security roles for Web applications
1. Define security roles in the Security section of the Web
deployment descriptor.
Roles represent categories of users that can access the
Web application.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-4. Constrain access based on security role RD7927.0
Notes:
In the Web resource collection list, use a URL pattern to define which Web resources apply
to a particular security constraint. You can also define which HTTP method triggers the
security constraint. The authorized roles list which roles are allowed to access the Web
resources listed in the security constraint.
Not shown in the screen capture is the user data constraint. This setting specifies whether
there is an integrity or confidentiality constraint between the client and the server. In most
cases, you must configure secure sockets layer (SSL) to meet an integrity or confidentiality
requirement.
5
Constrain access based on security role
2. Set security constraints for the Web application:
a. List which Web resources apply to the security constraint
in the Web resource collection section.
b. Define which roles are authorized to use the Web
resource collection in the Authorized Roles section.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-5. Gather roles in the enterprise application RD7927.0
Notes:
Security roles must be gathered in the application deployment descriptor. Using this
interface, the deployer maps abstract J2EE security roles to concrete users and groups.
The actual list of users and groups are specific to the security package chosen.
6
Gather roles in the enterprise application
3. In the Application Deployment Descriptor section, click
Gather in the Security section.
4. Map the actual users and groups to the security roles.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-11
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-12 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-6. Web container client authentication RD7927.0
Notes:
Neither basic authentication nor form-based authentication encrypts the user password.
Therefore, these forms of authentication should always be used over a secure channel,
such as a secure sockets layer (SSL) connection.
In the digest authentication scheme, the server generates an MD5 hash value for the user
name, password and URI resource address. Clients create and send an MD5 hash to
authenticate itself in a request. Since MD5 creates a unique value that cannot be reversed,
other users cannot figure out your password simply from the hash value.
Certificate-based authentication is an alternative to using user name and passwords to
authenticate users. A digital certificate uniquely identifies one user from another. Only
trusted third parties, known as certificate authorities (CA), issue and sign digital certificates.
This scheme prevents individual users from manufacturing their own certificates.
7
Web container client authentication
Authentication methods for a Web application client:
Basic authentication
Client sends user name and password in the HTTP header using
base64 encoding.
Form-based authentication
Client sends user name and password in an HTML form
Sent in an HTTP Post request in plain text.
Digest authentication
Client sends an MD5 hash based on the user name, password, URI
resource and other information.
Certificate-based authentication
Client uses a digital certificate to uniquely identify itself
A trusted third-party, known as a certificate authority (CA) issues
digital certificates.
Digital certificates include a unique serial number, identification
information and the users public key.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-13
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-14 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-7. Configure client authentication method RD7927.0
Notes:
During HTTP basic authentication, the server sends an authorization request to the client
along with the realm name. For users accessing the Web resource using a Web browser, a
login dialog box appears. After the user returns the user name and password, the Web
browser transmits the information to the server.
In form-based authentication, the specified login page appears on the first time that the
user accesses the protected Web resource. If authentication fails, the server returns the
specified error page.
Some client authentication methods, such as digest authentication, requires manually
editing configuration files in WebSphere Application Server. For complete steps, refer to the
redbook SG24-6316-01 (IBM WebSphere Application Server V6.1 Security Handbook).
8
Configure client authentication method
1. In the Web Deployment Descriptor section, set the Login
method in the Pages section.
a. For basic authentication, enter an arbitrary realm name.
b. For form authentication, specify both a login page and
an error page.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-15
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-16 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-8. Declarative and programmatic security RD7927.0
Notes:
The discussion on Web application security dealt with declarative security up to this point.
Declarative security separates business logic from security information, making
applications more portable and robust. However, there are some cases in which the
application needs to know the security context of a particular request. Using the sample
bank application, the account page might need to retrieve the account balance based on
the user name.
9
Declarative and programmatic security
Web application security configured using a declarative model
Web applications can view security information
programmatically
The following three methods from HttpServletRequest
provides information on the security context:
getRemoteUser()
Returns the user name the client used for authentication.
Returns null if no user is authenticated.
isUserInRole(String name)
Returns true if the remote user is granted the specified security
role.
If the remote user is not granted the specified role, or if no user is
authenticated, it returns false.
getUserPrincipal()
Returns the java.security.Principal object containing the
remote user name.
If no user is authenticated, it returns null.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-17
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-18 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-9. Define security role references RD7927.0
Notes:
The best practice is to use security role references instead of referring to an actual security
role when using programmatic security calls. For example, instead of calling
httpServletRequest.isUserInRole(Administrator), replace the role name of Administrator
with Manager. Define a security role reference for the Administrator role and name it as
Manager. This scheme allows the deployer to change the security information in the
deployment descriptor without affecting the compiled Web application.
10
Define security role references
Use security role references to avoid hard-coding J2EE
security role names into programmatic security calls
Reference acts as an alias to the actual security role name
Per servlet setting, set in the Security Role Reference list
within the Servlets section in the Web Deployment
Descriptor.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-19
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-20 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-10. Enterprise application security overview RD7927.0
Notes:
Java 2 Security is a programmatic security model introduced with J2SE 1.2. J2EE security
does not require Java 2 Security; the two systems can co-exist in an enterprise application.
11
Enterprise application security overview
WebSphere Application Server is built upon several layers of
security:
The Operating System protects WebSphere configuration
files and provides user authentication when using the local
OS user registry.
The Java Virtual Machine (JVM) provides standard Java
security.
Java 2 Security builds upon standard Java security.
Fine grained access control
Configurable security policy
Security checks for all Java applications
J2EE Security provides standard, container-level security.
Insulates enterprise applications from the actual security
implementation.
Classifies clients into roles, each with different access levels for a
given resource.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-21
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-22 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-11. WebSphere environment security layers RD7927.0
Notes:
This module focuses on the security layers most likely used by Web applications:
application level and transport level security. Application level security covers role-based
access provided by J2EE and WebSphere security. Transport level security covers
authentication mechanisms and encryption layers.
12
WebSphere environment security layers
Platform security
Operating system
Java security
Java Virtual Machine
Java 2 security
JCE JAAS JSSE
J2EE security
J2EE security
WebSphere security
Transport security
HTTP IIOP LDAP
Client security
Client application / external component
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-23
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-24 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-12. Security in WebSphere (1 of 2) RD7927.0
Notes:
13
Security in WebSphere (1 of 2)
Security is now enabled by default.
Managed in the administrative console
Can be set manually or you can use the Security
Configuration Wizard
Can generate a Security Configuration report to detail
environment
J2EE security
Global security provides J2EE security.
Java 2 security
Provides additional security beyond J2EE security.
Administrative console security
Users must enter user name and password to access the
administrative console.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-25
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-26 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-13. Security in WebSphere (2 of 2) RD7927.0
Notes:
14
Security in WebSphere (2 of 2)
Authentication of HTTP clients
Enforces basic, digest, form or certificate-based
authentication.
Role-based authorization checks for Web resources
Enforces security constraints set in Web deployment
descriptor.
Secure Sockets Layer (SSL)
Provides security for Web application resources that has a
confidentiality security restraint.
V6.1 also supports Simple and Protected GSS-API Negotiation
(SPNEGO)
Allows single signon from a Windows desktop browser that
supports SPNEGO authentication.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-27
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-28 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-14. Manage security in WebSphere RD7927.0
Notes:
15
Manage security in WebSphere
In the WebSphere administrative console, open Security ->
Secure administration, applications, and infrastructure
Run the wizard.
Restart the server.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-29
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-30 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-15. Checkpoint RD7927.0
Notes:
Write down your answers here:
16
Checkpoint
1. What types of security constraints can you set to a Web resource
collection?
2. What is the purpose of gathering security roles in the application
deployment descriptor?
3. What is the purpose of creating a security role reference?
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-31
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-32 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-16. Checkpoint solutions RD7927.0
Notes:
17
Checkpoint solutions
1. What types of security constraints can you set to a Web resource
collection?
There are two types of security constraints that can be set:
a) Authorized users determine which roles are allowed to access the
named resources.
b) User data constraints determine the confidentiality and integrity
requirements for the communication between the client and server.
2. What is the purpose of gathering security roles in the application
deployment descriptor?
Gathering security role references collects all security roles into the
application deployment descriptor. After completing this step, you can
map security roles to actual users and groups.
3. What is the purpose of creating a security role reference?
A security role reference avoids hard-coding a role name into the Web
application code. This idea is similar to how resource references avoid
the need to hardcode a JNDI lookup name into code.
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-33
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-34 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 29-17. Unit summary RD7927.0
Notes:
18
Having completed this unit, you should be able to:
Apply role-based security to a Web application
Gather roles in the application deployment descriptor
Configure a Web application authentication method
Set security role references for servlets
Configure security in the test environment
Having completed this unit, you should be able to:
Apply role-based security to a Web application
Gather roles in the application deployment descriptor
Configure a Web application authentication method
Set security role references for servlets
Configure security in the test environment
Unit summary
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 29. Web Application Security 29-35
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
29-36 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 30. Course Summary 30-1
V4.0
Uempty
Unit 30.Course Summary
Estimated time
00:15
What this unit is about
This unit summarizes the course.
What you should be able to do
After completing this unit, you should be able to state some valuable
resources for more information and education.
How you will check your progress
Accountability:
Discussion
References
http://www.ibm.com/services/learning
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
30-2 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 30-1. What this course was about RD7927.0
Notes:
2
What this course was about
Developing servlets and JSP pages and discussing best
practices
Developing JavaBeans
Developing JSP custom tags and tag files
Developing servlet filters and listeners
Integrating servlets, JSPs, and JavaBeans to construct an
application with a model-view-controller design pattern
Using IBM Rational Application Developer
Using J2EE security to secure Web applications
Integration testing in IBM WebSphere Application Server V6.1
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 30. Course Summary 30-3
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
30-4 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 30-2. Resources RD7927.0
Notes:
e-businesshome: www.ibm.com/software/ebusiness
3
Resources
Web Pages
WebSphere Family
http://www.ibm.com/websphere
WebSphere developerWorks
http://www.ibm.com/
developerworks/websphere
Java Specifications
http://java.sun.com/j2ee
http://java.sun.com/products/
servlet
http://java.sun.com/products/jsp
http://java.sun.com/products/jndi
World Wide Web Consortium
http://www.w3c.org
Training
IBM Learning Services
http://www.ibm.com/services/
learning
ITSO Redbooks:
www.redbooks.ibm.com
WebSphere certification
http://www.ibm.com/certify/certs/
ws_index.shtml
News Groups
ibm.software.websphere.
application-server
ibm.software.websphere.studio
ibm.software.websphere.studio.
application-site-developer
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 30. Course Summary 30-5
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
30-6 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 30-3. Other WebSphere courses RD7927.0
Notes:
4
Other WebSphere courses
DEV451: Mastering EJB Development with Rational
Application Developer v7
DEV452: Mastering Web Application Development with
Rational Application Developer v7
DEV453: Mastering JSF Development with Rational
Application Developer v7
DEV454: Mastering Struts Application Development with
Rational Application Developer v7
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 30. Course Summary 30-7
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
30-8 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
Figure 30-4. Finally RD7927.0
Notes:
5
Finally
Please provide feedback via course evaluation
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Copyright IBM Corp. 2003, 2007 Unit 30. Course Summary 30-9
V4.0
Uempty
Instructor notes:
Purpose
Details
Additional information
Transition statement
Instructor Guide
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
30-10 Servlet and JSP Development Copyright IBM Corp. 2003, 2007
V4.1
backpg
Back page

You might also like