Académique Documents
Professionnel Documents
Culture Documents
1
Agenda
? Including, forwarding to, and redirecting to
other web resources
? Servlet life-cycle events
? Concurrency Issues with
SingleThreadModel
? Invoker Servlet
This is the list of topics we will discuss in this session of “Advanced Servlet”. First, we
will talk about Session Tracking. Session Tracking is used in pretty much in all web
applications you see out there today.
Then we will talk about Servlet filters, which is one of the most useful features.
We will also talk about Servlet life-cycle events. Servlet life-cycle events let you have
event notification from various state change such as a session creation so that you can
build more intelligent Servlet application.
We will spend brief time on how to include, forward to, and redirect to other web
resources. Finally we will talk about concurrency issues (or synchronization) issues.
2
Including, Forwarding,
Redirecting to other
Web resources
Now let's talk about how you can include, dispatch to, or redirecting to
another web resource.
3
Including another
Web Resource
4
4
When to Include another Web
resource?
? When it is useful to add static or dynamic
contents already created by another web
resource
– Adding a banner content or copyright information in
the response returned from a Web component
It is often useful to include another Web resource, for example, banner content or
copyright information, in the response returned from a Web component.
5
Types of Included Web Resource
? Static resource
– It is like “programmatic” way of adding the static
contents in the response of the “including” servlet
? Dynamic web component (Servlet or JSP
page)
– Send the request to the “included” Web component
– Execute the “included” Web component
– Include the result of the execution from the
“included” Web component in the response of the
“including” servlet
6
6
Things that Included Web
Resource can and cannot do
? Included Web resource has access to the
request object, but it is limited in what it can
do with the response
– It can write to the body of the response and commit a
response
– It cannot set headers or call any method (for example,
setCookie) that affects the headers of the response
An included Web component has access to the request object, but it is limited in
what it can do with the response object:
7
How to Include another Web
resource?
? Get RequestDispatcher object from
ServletConext object
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banne
r");
? Then, invoke the include() method of the
RequestDispatcher object passing request
and response objects
– dispatcher.include(request, response); 8
include(request, response);
8
Example: BannerServlet as “Included”
Web component
public class BannerServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
9
Example: Including “BannerServlet”
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
dispatcher.include(request, response);
}
10
Each servlet in the Duke's Bookstore application includes the result from
BannerServlet with the following code:
10
Forwarding to
another
Web Resource
11
Now let's talk about how to forward control to another web resource.
11
When to use “Forwarding” to
another Web resource?
? When you want to have one Web
component do preliminary processing of a
request and have another component
generate the response
? You might want to partially process a
request and then transfer to another
component depending on the nature of the
request
12
12
Rules of “Forwarding” to
another Web resource?
? Should be used to give another resource
responsibility for replying to the user
– If you have already accessed a
ServletOutputStream or PrintWriter object within
the servlet, you cannot use this method; it throws
an IllegalStateException
13
The forward method should be used to give another resource responsibility for
replying to the user. If you have already accessed a ServletOutputStream or
PrintWriter object within the servlet, you cannot use this method; it throws an
IllegalStateException.
13
How to do “Forwarding” to
another Web resource?
? Get RequestDispatcher object from
HttpServletRequest object
– Set “request URL” to the path of the forwarded page
RequestDispatcher dispatcher
= request.getRequestDispatcher("/template.jsp");
? If the original URL is required for any processing, you
can save it as a request attribute
? Invoke the forward() method of the
RequestDispatcher object
– dispatcher.forward(request, response);
14
To transfer control to another Web component, you invoke the forward method of
a RequestDispatcher. When a request is forwarded, the request URL is set to the
path of the forwarded page. If the original URL is required for any processing,
you can save it as a request attribute.
14
Example: Dispatcher Servlet
public class Dispatcher extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
request.setAttribute("selectedScreen",
request.getServletPath());
RequestDispatcher dispatcher = request.
getRequestDispatcher("/template.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
...
}
15
15
Instructing Browser to
Redirecting to another
Web Resource
16
Now let's talk about how your servlet can instruct the browser to automatically
redirect to another web resource.
16
Redirecting a Request
? Two programming models for directing
a request
? Method 1:
res.setStatus (res.SC_MOVED_PERMANTLY);
res.setHeader ("Location", "http://...");
? Method 2:
public void sendRedirect(String url)
17
17
Servlet Filters
18
OK. Now let's talk about one of the most useful features of servlet
technology, servlet filters.
18
Sub-Agenda: Servlet Filters
? What is & Why servlet filters (with use case
scenarios)?
? How are servlet filters chained?
? Servlet filter programming APIs
? Servlet filter configuration in web.xml
? Steps for building and deploying servlet
filters
? Example code
19
19
What is and Why
Servlet Filter?
20
Let's talk about first what a servlet filter is and when do you want to use servlet
filters.
20
What are Java Servlet Filters?
? New component framework for intercepting
and modifying requests and responses
– Filters can be chained and plugged in to the
system during deployment time
? Allows range of custom activities:
– Marking access, blocking access
– Caching, compression, logging
– Authentication, access control, encryption
– Content transformations
? Introduced in Servlet 2.3 (Tomcat 4.0) 21
What are servlet filters? Servlet filters are used to intercept incoming
HTTP requests and outgoing HTTP responses and perform custom actions
such as caching, compression, logging, authentication, access control,
encryption, and so on.
Since this is rather useful feature, vendor products used to support this
feature even before Servlet 2.3 but obviously those vendor specific filters
were not really portable. Now servlet 2.3 formalized it so that servlet
filters can be portable and as we will see later on filters can be chained and
plugged in during deployment time.
21
What Can a Filter Do?
? Examine the request headers
? Customize the request object if it wishes to
modify request headers or data
? Customize the response object if it wishes to
modify response headers or data
? Invoke the next entity in the filter chain
? Examine response headers after it has
invoked the next filter in the chain
? Throw an exception to indicate an error in
processing
22
22
Use Case Scenario 1 of Filters[4]
? You have many servlets and JSP pages that
need to perform common functions such as
logging or XSLT transformation
– You want to avoid changing all these servlets and
JSP pages
– You want to build these common functions in a
modular and reusable fashion
? Solution
– build a single logging filter and compression filter
– plug them at the time of deployment
23
Now let's talk about a few use cases where using servlet filters could be
very useful.
23
Use Case Scenario 2 of Filters[4]
? How do you separate access control
decisions from presentation code (JSP pages)
– You do not want to change individual JSP pages
since it will mix “access-control” logic with
presentation logic
? Solution
– build and deploy a “access-control” servlet
24
24
Use Case Scenario 3 of Filters[4]
? You have many existing Web resources that
need to remain unchanged except a few
values (such as banners or company name)
– You cannot make changes to these Web
resources every time company name gets
changed
? Solution
– Build and deploy “banner replacement filter” or
“company name replacement filter”
25
25
How are
Servlet Filters
chained?
26
Now let's talk about how servlet filters can be chained and deployed.
26
How Servlet Filter Work?
Servlet Servlet
Container Filter Chain
doFilter(
User Servlet service(
ServletRequest,
implemented container ServletRequest,
ServletResponse,
filters filter ServletResponse)
FilterChain) 27
This picture shows how filter scheme works. The servlet container takes a look at the
web.xml file and figures out which set of filters are configured and how they are to be
called in order. So it calls filter 1, then filter 2, then filter N, which then passes the
HTTP request to the servlet.
27
How Filter Chain Works
? Multiple filters can be chained
– order is dictated by the order of <filter> elements in
the web.xml deployment descriptor
? The first filter of the filter chain is invoked by
the container
– via doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
– the filter then perform whatever filter logic and then
call the next filter in the chain by calling
chain.doFilter(..) method
? The last filter's call to chain.doFilter() ends up
calling service() method of the Servlet 28
The doFilter() method of the first filter in the chain is invoked by the
container. The filter then performs whatever filter logic it wants to
perform whether it is logging or compression or XSLT transformation.
It then calls doFilter() method of the FilterChain object, which results in
calling doFilter() method of the next filter in the chain.
The last filter in the chain ends up calling the service() method of the
servlet.
28
Servlet Filter
Programming APIs
29
29
javax.servlet.Filter Interface
? init(FilterConfig)
– called only once when the filter is first initialized
– get ServletContext object from FilterConfig
object and save it somewhere so that doFilter()
method can access it
– read filter initialization parameters from
FilterConfig object through getInitParameter()
method
? destroy()
– called only once when container removes filter
object
– close files or database connections 30
Filter interface defines init() and destroy() methods. The init() methods is
called only once when the filter is first initialized. Typical actions that can
be taken by the servlet when init() method is called are getting
ServletContext object (from FilterConfig object) and save it so that
doFilter() method can access the attrbutes that are maintained in thE
ServletContext or reading filter initialization parameters.
The destroy() method on the other hand gets called when the container
removes the filter object, for example, when the server goes down.
30
javax.servlet.Filter Interface
? doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
– gets called each time a filter is invoked
– contains most of filtering logic
– ServletRequest object is casted to HttpServletRequest
if the request is HTTP request type
– may wrap request/response objects
– invoke next filter by calling chain.doFilter(..)
– or block request processing
? by omitting calling chain.doFilter(..)
The doFilter() method of the Filter interface, unlike init() and destroy()
methods, get called each time a filter is invoked, that is, each time a request
is received. And this is the method that contains the filtering logic.
The input parameter is ServletRequest type but typically you want to cast it
to HttpServletRequest so that you can call HTTP specific methods. One
thing you can do within doFilter() method is to wrap incoming request and
response objects before passing them to the next filter in chain.
Once you are done with your filtering logic, you can then call doFilter()
method of the FilterChain object, upon which the container then invokes
the next filter in chain. Or the filter blocks request processing by omitting
calling doFilter() method of the FilterChain object and directly return to
the client. In this case, the filter has to provide the output response to the
client.
31
Other Sevlet Filter Related Classes
? javax.servlet.FilterChain
– passed as a parameter in doFilter() method
? javax.servlet.FilterConfig
– passed as a parameter in init() method
? javax.servlet.HttpServletResponseWrapper
– convenient implementation of the
HttpServletResponse interface
32
You already have seen how FilterChain class is used. FilterChain object,
which is constructed by the container is passed as a parameter every time
doFilter() method of a filter is invoked by the container.
32
Servlet Filter
Configuration in
the web.xml file
33
OK. Now let's talk about servlet configuration in the web.xml deployment
descriptor.
33
Configuration in web.xml
? <filter>
– <filter-name>: assigns a name of your choosing to the
filter
– <filter-class>: used by the container to identify the filter
class
? </filter>
? <filter-mapping>
– <filter-name>: assigns a name of your choosing to the
filter
– <url-pattern>: declares a pattern URLs (Web resources)
to which the filter applies
? </filter-mapping> 34
There are two filter related elements: <filter> element and <filter-
mapping> element. The <filter> element defines filter name and filter
class. The filter class will be instantiated by the container at appropriate
time. The <filter-mapping> element defines which web resources URLs
the filter is to be applied.
34
Example: web.xml of BookStore
<web-app>
<display-name>Bookstore1</display-name>
<description>no description</description>
<filter>
<filter-name>OrderFilter</filter-name>
<filter-class>filters.OrderFilter</filter-class>
</filter>
<filter>
<filter-name>HitCounterFilter</filter-name>
<filter-class>filters.HitCounterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OrderFilter</filter-name>
<url-pattern>/receipt</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/enter</url-pattern>
</filter-mapping>
<listener>
...
</listener> 35
<servlet>
35
Steps for Building
and Deploying
Servlet Filters
36
36
Steps for Building a Servlet Filter
? Decide what custom filtering behavior you
want to implement for a web resource
? Create a class that implements Filter
interface
– Implement filtering logic in the doFilter() method
– Call the doFilter() method of FilterChain object
? Configure the filter with Target servlets and
JSP pages
– use <filter> and <filter-mapping> elements
37
37
Servlet Filter
Example Code
38
38
Example: HitCounterFilter
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
39
39
Example: HitCounterFilter
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
40
In the doFilter() method, the Counter object is retrieved from the ServletContext
object. The value of the counter is then displayed and incremented.
40
HitCounterFilter Configuration
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<display-name>Bookstore1</display-name>
<description>no description</description>
<filter>
<filter-name>HitCounterFilter</filter-name>
<filter-class>filters.HitCounterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/enter</url-pattern>
</filter-mapping>
...
41
This slides shows the <filter> and <filter-mapping> elements in web.xml file for
the HitCounterFilter.
41
Servlet
LifeCycle Events
42
42
Servlet Lifecycle Events
? Support event notifications for state
changes in
– ServletContext
? Startup/shutdown
? Attribute changes
– HttpSession
? Creation and invalidation
? Changes in attributes
43
43
Steps for Implementing Servlet
Lifecycle Event
1.Decide which scope object you want to receive
an event notification
2.Implement appropriate interface
3.Override methods that need to respond to the
events of interest
4.Obtain access to important Web application
objects and use them
5.Configure web.xml accordingly
6.Provide any needed initialization parameters
44
44
Listener Registration
? Web container
– creates an instance of each listener class
– registers it for event notifications before
processing first request by the application
– Registers the listener instances according to
? the interfaces they implement
45
Listener Interfaces
? ServletContextListener
– contextInitialized/Destroyed(ServletContextEvent)
? ServletContextAttributeListener
– attributeAdded/Removed/Replaced(
ServletContextAttributeEvent)
? HttpSessionListener
– sessionCreated/Destroyed(HttpSessionEvent)
? HttpSessionAttributeListener
– attributedAdded/Removed/Replaced(
HttpSessionBindingEvent)
? HttpSessionActivationListener
– Handles sessions migrate from one server to another
– sessionWillPassivate(HttpSessionEvent)
– sessionDidActivate(HttpSessionEvent) 46
This slide lists the listener interfaces. The first two are listener interfaces for the
ServletContext while the next two are for HttpSession object.
46
Example: Context Listener
public final class ContextListener
implements ServletContextListener {
private ServletContext context = null;
try {
BookDB bookDB = new BookDB();
context.setAttribute("bookDB", bookDB);
} catch (Exception ex) {
context.log("Couldn't create bookstore
database bean: " + ex.getMessage());
}
47
Example: Context Listener
public void contextDestroyed(ServletContextEvent event) {
context = event.getServletContext();
BookDB bookDB =
(BookDB)context.getAttribute("bookDB");
bookDB.remove();
context.removeAttribute("bookDB");
context.removeAttribute("hitCounter");
context.removeAttribute("orderCounter");
}
}
48
48
Listener Configuration
<web-app>
<display-name>Bookstore1</display-name>
<description>no description</description>
<filter>..</filter>
<filter-mapping>..</filter-mapping>
<listener>
<listener-class>listeners.ContextListener</listener-class>
</listener>
<servlet>..</servlet>
<servlet-mapping>..</servlet-mapping>
<session-config>..</session-config>
<error-page>..</error-page>
...
</web-app>
49
49
Servlet
Synchronization &
Thread Model
50
50
Concurrency Issues on a Servlet
? The service() method of a servlet instance
can be invoked by multiple clients (multiple
threads)
? Servlet programmer has to deal with
concurrency issue
– shared data needs to be protected
– this is called “servlet synchronization”
? 2 options for servlet synchronization
– use of synchronized block
– use of SingleThreadModel 51
There are two different ways a servlet synchronization can be handled. The first
method is using synchronized block while the other method is the use of
SingleThreadModel for the entire servlet.
51
Many Threads,
One Servlet Instance
Web Server
request
thread
request thread
request thread
Servlet
thread
request
thread
request
Servlet container
52
A web server can call a servlet's service() method for several requests at once. This brings up the issue of thread
safety in servlets. But first consider what you do not need to worry about: a servlet's init() method. The init()
method will only be called once for the duration of the time that a servlet is loaded. The web server calls init()
when loading, and will not call it again unless the servlet has been unloaded and reloaded. In addition, the
service() method or destroy() method will not be called until the init() method has completed its processing.
Things get more interesting when you consider the service() method. The service() method can
be called by the web server for multiple clients at the same time. If your service() method uses outside resources,
such as instance data from the servlet object, files, or databases, you need to carefully examine what might
happen if multiple calls are made to service() at the same time. For example, suppose you had defined a counter
in your servlet class that keeps track of how many service() method invocations are currently running:
private int counter = 0;
Next, suppose that your service() method contained the following code:
int myNumber = counter + 1; // line 1
counter = myNumber; // line 2
// rest of the code in the service() method
counter = counter – 1;
What would happen if two service() methods were running at the same time, and both executed line 1 before
either executed line 2? Both would have the same value for myNumber, and the counter would not be properly
updated. For this situation, the answer might be to synchronize the access to the counter variable:
synchronized(this) {
myNumber = counter + 1;
counter = myNumber;
}
// rest of code in the service() method
synchronized(this) {
counter = counter - 1 ;
}
This ensures that the counter access code is executed only one thread at a time.
52
Use of synchronized block
? Synchronized blocks are used to
guarantee only one thread at a time
can execute within a section of code
synchronized(this) {
myNumber = counter + 1;
counter = myNumber;
}
...
synchronized(this) {
counter = counter - 1 ;
}
53
53
SingleThreadModel Interface
? Servlets can also implement
javax.servlet.SingleThreadModel
? The server will manage a pool of servlet
instances
? Guaranteed there will only be one thread per
instance
? This could be overkill in many instances
Public class SingleThreadModelServlet extends
HttpServlet implements SingleThreadModel {
...
}
54
54
SingleThreadModel
Web Server
thread
thread
thread
thread
55
55
Best Practice Recommendation
? Do use synchronized block whenever
possible
– SingleThreadModel is expensive (performance
wise)
56
56
Invoker Servlet
57
57
What is Invoke Servlet?
? Executes anonymous servlet classes that
have not been defined in a web.xml file
? Mostly used for debugging and testing
purpose
? Example scenario
– I have very large number of servlets (i.e. 1000
servlets)
– I do not want to specify servlet mapping for all 1000
servlets in my web.xml especially at the time of
development
– If I use invoker servlet (which is provided by the 58
container), a user can access 1000 servlets without
58
How to Use Invoke Servlet?
? Uncomment the following from
<Tomcat>/conf/web.xml and restart Tomcat
<!--
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet> 59
-->
59
How to Use Invoke Servlet?
? Add the following to the web.xml of the
application
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/myservlets/*</url-pattern>
</servlet-mapping>
60
60
Passion!
61
61