Vous êtes sur la page 1sur 61

Servlet (Advanced)

Welcome to Servlet advanced session. We learned basic concepts of


Servlet in our previous class. Today we are going to learn advanced
concepts of Servlet.

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

Now let's talk about how to include 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

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

If the resource is static, the include method enables programmatic server-side


includes. If the resource is a Web component, the effect of the method is to send
the request to the included Web component, execute the Web component, and
then include the result of the execution in the response from the containing
servlet. An included

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:

* 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("/banne
r");
? Then, invoke the include() method of the
RequestDispatcher object passing request
and response objects
– dispatcher.include(request, response); 8

To include another resource, invoke the include method of a RequestDispatcher


object:

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 {

PrintWriter out = response.getWriter();


out.println("<body bgcolor=\"#ffffff\">" +
"<center>" + "<hr> <br> &nbsp;" + "<h1>" +
"<font size=\"+3\" color=\"#CC0066\">Duke's </font>" +
<img src=\"" + request.getContextPath() +
"/duke.books.gif\">" +
"<font size=\"+3\" color=\"black\">Bookstore</font>" +
"</h1>" + "</center>" + "<br> &nbsp; <hr> <br> ");
}
public void doPost (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();


out.println("<body bgcolor=\"#ffffff\">" +
"<center>" + "<hr> <br> &nbsp;" + "<h1>" +
"<font size=\"+3\" color=\"#CC0066\">Duke's </font>" +
<img src=\"" + request.getContextPath() +
"/duke.books.gif\">" +
"<font size=\"+3\" color=\"black\">Bookstore</font>" +
"</h1>" + "</center>" + "<br> &nbsp; <hr> <br> ");
} 9
}

The banner for the Duke's Bookstore application is generated by BannerServlet.


Note that both the doGet() and doPost() methods are implemented because
BannerServlet can be dispatched from either method in a calling servlet.

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

In some applications, you might want to have one Web component do


preliminary processing of a request and have another component generate the
response. For example, 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

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

The Dispatcher servlet, used by a version of the Duke's Bookstore application


described in The Example JSP Pages, saves the path information from the
original URL, retrieves a RequestDispatcher from the request, and then forwards
to the JSP page template.jsp.

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

There are two different programming models for directing a request to a


different web resource. The first model is to set the status and header fields of
a response directly. And the other programming model is to call sendRedirect()
method of a HttpServletResponse object. This method sends a temporary
redirect response to the client using the specified redirect location URL. This
method can accept relative URLs; the servlet container must convert the relative
URL to an absolute URL before sending the response to the client. If the
location is relative without a leading '/' the container interprets it as relative to
the current request URI. If the location is relative with a leading '/' the container
interprets it as relative to the servlet container root.

If the response has already been committed, this method throws an


IllegalStateException. After using this method, the response should be
considered to be committed and should not be written to.

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

This is the list of sub topics under Servlet filters.

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

This slides lists the things a filter can do.

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.

(read the slide)

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

(read the slide)

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

(read the slide)

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

Filter 1 Filter 2 Filter N

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

This slide is a more detailed explanation of the previous picture.

A filter chain is made of multiple filters which are chained together.


The order of these filters in the chain is specified in the order the filters
are defined in the web.xml deployment descriptor.

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

OK. Programming APIs.

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

? filter has to provide output the client

– set headers on the response for next entity


31

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.

FilterConfig object is constructed by the container and passed as a


parameter to init() method of each filter.

HttpServletResponseWrapper is a convenience class of


HttpServletResponse interface.

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>

This is an example filter definitions from BookStore example. Here we


define OrderFilter and HitCounterFilter elements. The <filter> element
should be defined before <filter-mapping> element. And these two have to
be defined before <listener> element and <servlet> and <servlet-mapping>
element.

35
Steps for Building
and Deploying
Servlet Filters
36

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

Building and deploying servlet filter is relatively straightforward. First,


you decide which custom filtering logic you want to implement for the
web resources.

Then create a class that implements Filter interface. And implement


whatever filtering logic in doFilter() method. And again once filtering
logic is done, call doFilter() method of the FilterChain object so that
container can call the next filter in the chain.

Then you define the <filter> and <filter-mapping> elements in the


web.xml deployment descriptor.

37
Servlet Filter
Example Code
38

Now let's take a look at example code of a servlet filter in BookStore


application.

38
Example: HitCounterFilter
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig)


throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}

// Continued in the next page...

39

Here HitCounterFilter implements Filter interface. The init() method of the


filter just saves the passed FilterConfig object in local variable.

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) filterConfig.getServletContext().getAttribute("hitCounter");
writer.println("The number of hits is: " +
counter.incCounter());

// Log the resulting string


writer.flush();
filterConfig.getServletContext().log(sw.getBuffer().toString());
...
chain.doFilter(request, wrapper);
...
}
}

40

In the doFilter() method, the Counter object is retrieved from the ServletContext
object. The value of the counter is then displayed and incremented.

And then the doFilter() method of the FilterChain object is called.

40
HitCounterFilter Configuration
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web


Application 2.3//EN' 'http://java.sun.com/dtd/web-
app_2_3.dtd'>

<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

Now let's talk about Servlet lifecycle event.

42
Servlet Lifecycle Events
? Support event notifications for state
changes in
– ServletContext
? Startup/shutdown
? Attribute changes
– HttpSession
? Creation and invalidation
? Changes in attributes

43

Under servlet lifecycle event notification framework, 4 different types of


events can be captured. First, startup and shutdown of a servlet. Second,
changes in the attributes maintained in ServletContext. Third, session
creation and invalidation and fourth, changes in attributes maintained in
HttpSession object.

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

(read the slide)

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 web.xml


? Listeners are invoked in the order of their
registration during execution
45

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;

public void contextInitialized(ServletContextEvent event) {


context = event.getServletContext();

try {
BookDB bookDB = new BookDB();
context.setAttribute("bookDB", bookDB);
} catch (Exception ex) {
context.log("Couldn't create bookstore
database bean: " + ex.getMessage());
}

Counter counter = new Counter();


context.setAttribute("hitCounter", counter);
counter = new Counter();
context.setAttribute("orderCounter", counter);
} 47

This is an example code for ServletContextListener object. Here we are


creating a database connection object which will be shared by all servlets
in this web application when the web application is started the first time.
This database is then maintained as an attribute in the ServletContext
object. Two counters are also created as attributes for ServletContext
object.

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

When ServletContext object is removed - this happens when a Web


application is undeployed, for example -, we remove database connection
and also remove attributes.

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

This is an example of <listener> element in the web.xml deployment descriptor.


The <listener> element should be present after <filter> and <filter-mapping>
elements but before <servlet> element.

49
Servlet
Synchronization &
Thread Model

50

Now let's talk about servlet synchronization and 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

The service() method of a servlet instance can be invoked by multiple clients.


What this means is that the service() method can be invoked by multiple thread.
Consequently servlet programmer has to deal with concurrency issue, for
example, a shared data needs to be protected so that race condition does not result
in a corrupted data. This concurrency control is called servlet synchronization.

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

Now let's talk about servlet synchronization and thread model.

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>

? From your browser, access a servlet via


– http://localhost:8080/myservlets/newservlet2

60

60
Passion!

61

61

Vous aimerez peut-être aussi