Servlet (Advanced)
1
Agenda
● Including, forwarding to, and redirecting to
other web resources
● Servlet life-cycle events
● Concurrency Issues with SingleThreadModel
● Invoker Servlet
2
Including, Forwarding,
Redirecting to other
Web resources
3
Including another
Web Resource
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
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
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
7
How to Include another Web resource?
● Get RequestDispatcher object from
ServletConext object
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banner");
● Then, invoke the include() method of the
RequestDispatcher object passing request and
response objects
– [Link](request, response);
8
Example: BannerServlet as “Included” Web
component
public class BannerServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = [Link]();
[Link]("<body bgcolor=\"#ffffff\">" +
"<center>" + "<hr> <br> " + "<h1>" +
"<font size=\"+3\" color=\"#CC0066\">Duke's </font>" +
<img src=\"" + [Link]() +
"/[Link]\">" +
"<font size=\"+3\" color=\"black\">Bookstore</font>" +
"</h1>" + "</center>" + "<br> <hr> <br> ");
}
public void doPost (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = [Link]();
[Link]("<body bgcolor=\"#ffffff\">" +
"<center>" + "<hr> <br> " + "<h1>" +
"<font size=\"+3\" color=\"#CC0066\">Duke's </font>" +
<img src=\"" + [Link]() +
"/[Link]\">" +
"<font size=\"+3\" color=\"black\">Bookstore</font>" +
"</h1>" + "</center>" + "<br> <hr> <br> ");
}
}
9
Example: Including “BannerServlet”
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
[Link](request, response);
}
10
Forwarding 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
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
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
= [Link]("/[Link]");
● 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
– [Link](request, response);
14
Example: Dispatcher Servlet
public class Dispatcher extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
[Link]("selectedScreen",
[Link]());
RequestDispatcher dispatcher = request.
getRequestDispatcher("/[Link]");
if (dispatcher != null)
[Link](request, response);
}
public void doPost(HttpServletRequest request,
...
}
15
Instructing Browser to
Redirecting to another
Web Resource
16
Redirecting a Request
● Two programming models for directing a
request
● Method 1:
[Link](res.SC_MOVED_PERMANTLY);
[Link]("Location", "[Link]
● Method 2:
public void sendRedirect(String url)
17
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 [Link]
● Steps for building and deploying servlet filters
● Example code
19
What is and Why
Servlet Filter?
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 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
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
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
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
How are
Servlet Filters
chained?
26
How Servlet Filter Work?
Servlet Servlet
Container Filter Chain
Filter 1 Filter 2 Filter N
doFilter(
User Servlet service(
ServletRequest,
implemented container ServletRequest,
ServletResponse,
filters filter ServletResponse)
FilterChain) 27
How Filter Chain Works
● Multiple filters can be chained
– order is dictated by the order of <filter> elements in the
[Link] 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 [Link](..)
method
● The last filter's call to [Link]() ends up
calling service() method of the Servlet
28
Servlet Filter
Programming APIs
29
[Link] 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
[Link] 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 [Link](..)
– or block request processing
● by omitting calling [Link](..)
● filter has to provide output the client
– set headers on the response for next entity
31
Other Sevlet Filter Related Classes
● [Link]
– passed as a parameter in doFilter() method
● [Link]
– passed as a parameter in init() method
● [Link]
– convenient implementation of the HttpServletResponse
interface
32
Servlet Filter
Configuration in the
[Link] file
33
Configuration in [Link]
● <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
Example: [Link] of BookStore
<web-app>
<display-name>Bookstore1</display-name>
<description>no description</description>
<filter>
<filter-name>OrderFilter</filter-name>
<filter-class>[Link]</filter-class>
</filter>
<filter>
<filter-name>HitCounterFilter</filter-name>
<filter-class>[Link]</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>
<servlet>
35
...
Steps for Building and
Deploying Servlet
Filters
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
Servlet Filter
Example Code
38
Example: HitCounterFilter
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
[Link] = filterConfig;
}
public void destroy() {
[Link] = null;
}
// Continued in the next page...
39
Example: HitCounterFilter
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (filterConfig == null) return;
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
Counter counter =
(Counter) [Link]().getAttribute("hitCounter");
[Link]("The number of hits is: " +
[Link]());
// Log the resulting string
[Link]();
[Link]().log([Link]().toString());
...
[Link](request, wrapper);
...
}
}
40
HitCounterFilter Configuration
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN' '[Link]
app_2_3.dtd'>
<web-app>
<display-name>Bookstore1</display-name>
<description>no description</description>
<filter>
<filter-name>HitCounterFilter</filter-name>
<filter-class>[Link]</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/enter</url-pattern>
</filter-mapping>
...
41
Servlet
LifeCycle Events
42
Servlet Lifecycle Events
● Support event notifications for state changes in
– ServletContext
● Startup/shutdown
● Attribute changes
– HttpSession
● Creation and invalidation
● Changes in attributes
43
Steps for Implementing Servlet Lifecycle
Event
[Link] which scope object you want to receive an
event notification
[Link] appropriate interface
[Link] methods that need to respond to the
events of interest
[Link] access to important Web application
objects and use them
[Link] [Link] accordingly
[Link] any needed initialization parameters
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
● the order in which they appear in the
deployment descriptor [Link]
● Listeners are invoked in the order of their registration
during execution
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
Example: Context Listener
public final class ContextListener
implements ServletContextListener {
private ServletContext context = null;
public void contextInitialized(ServletContextEvent event) {
context = [Link]();
try {
BookDB bookDB = new BookDB();
[Link]("bookDB", bookDB);
} catch (Exception ex) {
[Link]("Couldn't create bookstore
database bean: " + [Link]());
}
Counter counter = new Counter();
[Link]("hitCounter", counter);
counter = new Counter();
[Link]("orderCounter", counter);
} 47
Example: Context Listener
public void contextDestroyed(ServletContextEvent event) {
context = [Link]();
BookDB bookDB = (BookDB)[Link]
("bookDB");
[Link]();
[Link]("bookDB");
[Link]("hitCounter");
[Link]("orderCounter");
}
}
48
Listener Configuration
<web-app>
<display-name>Bookstore1</display-name>
<description>no description</description>
<filter>..</filter>
<filter-mapping>..</filter-mapping>
<listener>
<listener-class>[Link]</listener-class>
</listener>
<servlet>..</servlet>
<servlet-mapping>..</servlet-mapping>
<session-config>..</session-config>
<error-page>..</error-page>
...
</web-app>
49
Servlet
Synchronization &
Thread Model
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
Many Threads,
One Servlet Instance
Web Server
request
thread
request thread
request thread
Servlet
thread
request
thread
request
Servlet container
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
SingleThreadModel Interface
● Servlets can also implement
[Link]
● 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
SingleThreadModel
Web Server
thread
thread
thread
thread
55
Best Practice Recommendation
● Do use synchronized block whenever possible
– SingleThreadModel is expensive (performance wise)
56
Invoker Servlet
57
What is Invoke Servlet?
● Executes anonymous servlet classes that have
not been defined in a [Link] file
● Mostly used for debugging and testing purpose
58
How to Use Invoke Servlet?
● Uncomment the following from
<Tomcat>/conf/[Link] and restart Tomcat
<!--
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
[Link]
</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
How to Use Invoke Servlet?
● Add the following to the [Link] of the
application
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
60
Passion!
61