You are on page 1of 59

Introduction to Web applications with

Java Technology
3- Servlets
Juan M. Gimeno, Josep M. Ribó

January, 2008
INDEX

Contents

Introduction to web applications with Java technology

1. Introduction.

2. HTTP protocol

3. Servlets

4. Servlet container: Tomcat

5. Web application deployment

1
INDEX

3- Servlets. Contents

• Introduction to servlets

• Servlet API
– Servlet
– GenericServlet
– HttpServlet
– HttpServletRequest
– HttpServletResponse
– ServletContext

• Example 1: Hello world

• Example 2: Sending an HTTP request

• Example 3: Parameter capture by name

• Servlet limitations and introduction to JSP

• Advanced topics on servlets:


– Filters
– Event listeners
– Servelts and concurrency

2
Intro. to Web applications in Java. 3- Servlets. Introduction INDEX

2.3 Servlets

What is a servlet

A servlet is a java class which may manage http


requests sent by a client and generate responses to
them.

• An http request from a client may refer (in its URI) a


servlet as the requested resource.

• The execution of that servlet will manage the request and


generate a response which is sent back to the client.

• Servlets are executed in the context of a servlet container.

• In particular, TOMCAT is a servlet container

3
Intro. to Web applications in Java. 3- Servlets. Introduction INDEX

Servlet lifecycle

Each time a request is addressed to a specific servlet, the


servlet container is responsible for

1. Loading the servlet class to which the request is associated


(only the first time that servlet is required)

2. Invoking the init(..) operation of that servlet class


to set up the servlet (e.g., create a connexion with a
database)

3. Managing the request by means of the service(..)


operation of that servlet class

4. Converting the response generated by the service(..)


operation into an http response and sending it back to the
client

5. Invoking the destroy(..) operation of the servlet class


to release servlet resources and to save the servlet state
(only when the server is shut down)

Notice that servlets are only loaded the first time they are
requested.

4
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API

Java defines a set of packages to work with servlets. In


particular, the following interfaces and classes are available:

• Servlet

• HttpServlet

• HttpServletRequest

• HttpServletResponse

• ServletContext

• ...

In the next few slides we present them

5
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. Servlet

• Outline:
The Servlet interface defines all the operations that must
be implemented by any servlet class
Usually, this interface is implemented by means of a class
that subclassifies the class HttpServlet

• Some methods:
– void init(ServletConfig config)
Called by the servlet container right after the servlet class has been
loaded and just before starting its operation
init is called just once during all the servlet life-cycle (i.e., it may
serve many requests but init is called only before serving the first
one)

6
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

– void service(ServletRequest req, ServletResponse res)


Called by the servlet container to allow the servlet to respond to a
request
This operation contains all the work that must be done by the
servlet
∗ req encapsulates the request sent by the client
∗ res encapsulates the response generated by the servlet

– void destroy()
Called by the servlet container to indicate to a servlet that the
servlet is being taken out of service.

– java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and
copyright.

7
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. GenericServlet

• Outline:
Defines a generic, protocol-independent servlet. To write
an HTTP servlet for use on the Web, extend HttpServlet
instead.

• Implements:
The interface Servlet

8
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. HttpServlet

• Outline:
HttpServlet is an abstract class to manage HTTP
servlets (i.e., servlets written for the web)
HTTP servlets written by a programmer should subclassify
HttpServlet instead of GenericServlet

• Superclass:
GenericServlet

9
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

• Some methods:
– protected void service(HttpServletRequest req,
HttpServletResponse res)
It is the responsible for:
∗ managing the request sent by the client and for
∗ creating a response which will be sent back to the client.
However, both issues are not actually carried out in this operation.
Instead, the service operation receives standard HTTP requests
from the client and dispatches them to the doGet/doPost operati-
ons defined in this class (according to the HTTP request method:
GET or POST)
Usually, this operation is not overriden by the classes that
subclassify HttpServlet. The overriden operations are doGet
and doPost

– protected void doGet(HttpServletRequest req,


HttpServletResponse resp)
Called by the server (via the service operation) to allow a servlet
to handle a GET request.
This operation is overriden by a specific class that subclassify
HttpServlet if the HTTP request sent to that specific servlet
uses the GET method

10
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

– protected void doPost(HttpServletRequest req,


HttpServletResponse resp)
Called by the server (via the service operation) to allow a servlet
to handle a POST request.
This operation is overriden by a specific class that subclassify
HttpServlet if the HTTP request sent to that specific servlet
uses the GET method

11
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. HTTPServletRequest

• Outline:
It is an interface that provides methods to encapsulate the
details about http requests. It controls the access to the
request elements (remote URL, header, parameters...)

• Superinterface:
ServletRequest (request independent of the protocol)

• Some methods:
– String getRequestURI();
Returns the part of this request’s URL from the protocol name up
to the query string in the first line of the HTTP request.

– String getQueryString();
Returns the query string that is contained in the request URL after
the path.

– String getMethod();
Returns the name of the HTTP method with which this request
was made, for example, GET or POST.

– Enumeration getHeaderNames();
Returns an enumeration of all the header names this request
contains.

12
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

– String getHeader(String name);


Returns the value of the specified request header as a String.

– Enumeration getParameterNames(); (Inherited)


Returns an Enumeration of String objects containing the names of
the parameters contained in this request.

– String getParameter(String name); (Inherited)


Returns the value of a request parameter as a String, or null if the
parameter does not exist.

– ServletInputStream getInputStream(); (Inherited)


Retrieves the body of the request as binary data using a ServletIn-
putStream.

– BufferedReader getReader(); (Inherited)


Retrieves the body of the request as character data using a Buffe-
redReader.

13
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servet API. HTTPServletResponse

• Outline:
It is an interface that acts as a wrapper of the output
stream of a servlet and of its length and type.

• Superinterface:
ServletResponse (response independent of the protocol)

• Some methods:
– String setContentLength();
Sets the length of the content body in the response In HTTP
servlets, this method sets the HTTP Content-Length header.

– String setContentType(); (Inherited)


Sets the content type of the response being sent to the client.

– void setHeader(String name, String value);


Sets a response header with the given name and value.

– Writer getWriter(); (Inherited)


Returns a PrintWriter object that can send character text to the
client.

14
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. ServletContext


• Outline:
– It is an interface that defines methods to share infor-
mation between all the servlets that compound a web
application (there is just one context for the whole web
application)
– In the case of distributed web applications (marked as
“distributed” in their deployment descriptors), there will
be a context for each Java virtual machine. In this case,
the servlet context cannot store the global information
for the whole application
– The servlet context for a specific application can be
obtained by means of the operations:
∗ GenericServlet.getServletContext()
∗ GenericServlet.getServletConfig().getServletContext()

• Some methods:
– void setAttribute(String name, Object obj);
Sets the object obj as a servlet context scope attribute accessible
with the given name

– Object getAttribute(String name);


Returns the value of the web context-scope attribute with the given
name

• public java.lang.String getInitParameter(java.lang.String


name)

15
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Returns a String containing the value of the initialization


parameter with name name, or null if the parameter does
not exist
This parameter can be set in the web.xml deployment
descriptor (see 5-Deployment of web applications)

<web-app>
...
<context-param>
<param-name>parameterName</param-name>
<param-value>parameterValue</param-value>
<description> Again, some description </description>
</context-param>
...
</web-app>

Parameters set in this way have a context-wide scope


They are retrieved by:

String val = getServletContext().getInitParameter("paramete

16
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. ServletConfig

• Outline:
– It is used to send initialization information from the
servlet container to the servlet itself
– In particular, to send servlet initialization parameters

• Some methods:
– ServletContext getServletContext()
– String getInitParameter(String name)
Returns a String containing the value of the named
initialization parameter, or null if the parameter does
not exist.

Servlet initialization parameters can be stated within the


servlet definition in the web.xml file:
<servlet>
<servlet-name>ServletName</servlet-name>
<description>ServletDescription</description>
<servlet-class>com.alexandria.package.MyServlet</servle
<init-param>
<param-name>parameterName</param-name>
<param-value>parameterValue</param-value>
</init-param>
</servlet>

17
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

String value = getServletConfig().getInitParameter("paramName

Servlet definition in the deployment descriptor web.xml is


presented in 5-Web application deployment

18
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Servlet API. RequestDispatcher

• Outline:

– When a servlet needs to send a request to some resource,


it does it through a RequestDispatcher object
– This interface is responsible for directing a request sent
by a servlet to a resource
– A specific object of this interface is obtained by a call
to:
ServletContext.getRequestDispatcher(..)
or
request.getRequestDispatcher(..)

• Some methods:
– void forward(ServletRequest request, ServletResponse respo
Forwards a request from a servlet to another resource (servlet, JSP
file, or HTML file) on the server.
Example: The servlet that calls forward has managed the request.
Another servlet is called to generate the response to the client
This strategy is used when the MVC pattern is applied (see ****)
– void include(ServletRequest request, ServletResponse respo
Includes the content of a resource (servlet, JSP page, HTML file)
in the response.
When the included resource has been managed, the control returns
to the servlet that launches the include call
Useful to include headers, footers...

19
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

Use of RequestDispatcher:

public class MyServlet extends HttpServlet {

public void doPost (HttpServletRequest request,


HttpServletResponse response){
...
RequestDispatcher dispatcher = request.
getRequestDispatcher("/someResource");
if (dispatcher != null)
dispatcher.forward(request, response);

...
}

dispatcher is an object that wraps requests to


/someResource

dispatcher.forward(request, response);

This instruction forwards the request request to


someResource. Notice that request is the same request
that MyServlet has received from the client

Before forwarding it to another resource, it is possible that


doPost modifies it

Example:

20
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX

request.setAttribute("catalogue", cat);
dispatcher.forward(request,response);

This strategy may be used when the MVC pattern is applied

21
Intro. to Web applications in Java. 3- Servlets. Example 1 INDEX

Example 1: Hello world


Example location: introapweb/examples/ex3.1

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.util.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doPost( request, response ) ;
}
public void doPost (HttpServletRequest request,
HttpServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1> HELLO WORLD!!! </h1>");
out.println("</body>");
out.println("</html>");
} catch (Exception ex) { ex.printStackTrace();}
}}

22
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

Example 2: Reading an http request

Example location: introapweb/examples/ex3.2

This example reads any http request and sends the contents
of this request back to the client

The contents of an http request consists of:

• Request line: Requested server file and request method


(GET/POST)

• Request header: Additional information about the client


(accepted language, accepted file formats...)

• Request body: It contains the parameters codified in


POST requests

23
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

Recall that parameters may be stored as:

• A query string in the request line (GET request codified


as query string)

• A query string in the body (POST request codified as


query string)

• A sequence of (name, value) pairs linked by a pseudo-


random string in the body (POST request codified as
multipart-data)

In this example we do not explore how to get each one


of the parameters by its name, but how to obtain the
elements that constitute the request.

Next example will be devoted to the capture of individual


parameters by name

24
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.util.*;

public class TranscriuPeticio extends HttpServlet {


private static final String PAGE_TOP=
"<html>"+
"<head"+
"<title> Transcripcio d’una peticio http</title>"+
"</head>"+
"<body bgcolor=\"white\">"+
"<h1> Contents of an http request </h1>"+
"<pre>"
;
private static final String PAGE_BOTTOM=
"*****FINAL PETICIO HTTP"+
" </pre>" +
" </body>"+
" </html>"
;

...(cont)

25
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException {
doPost( request, response ) ;
}

public void doPost (HttpServletRequest request,


HttpServletResponse response) {

String controlLine=new String("");


Enumeration enum;
String st=new String("");
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println (PAGE_TOP);
out.println("<b>1. Request line </b> <br><br>");
out.println("Method: "+request.getMethod());
out.println("Request URL: "+
request.getRequestURL());
out.println("Query string: "+
request.getQueryString());
...(cont)

26
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

out.println("<p><b>2.Request header</b><br><br>");
enum=request.getHeaderNames();
while(enum.hasMoreElements())
{
st=(String) enum.nextElement();
out.println(st+" : "+request.getHeader(st));
}
out.println("<p><b>3.Request body:</b> <br><br>");
java.io.BufferedReader br=request.getReader();
String temp=br.readLine();
while (temp!=null)
{
out.println(temp);
temp=br.readLine();
}
br.close();
out.println(PAGE_BOTTOM);
} catch (Exception ex) { ex.printStackTrace(); }
}
}

27
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

Example 2: Reading an http request

Remarks:

• The request body is captured as a character stream by


means of the method getReader() of the interface Serv-
letRequest:

BufferedReader br=request.getReader();

• If the request body were a byte sequence, then it would


be necessary to get an input stream (binary) by means of
the method getInputStream

28
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX

• When the request is received, we do not know either how


many headers will come up in the request or the value of
those headers. Therefore,
1. We get the header names:
(enum=request.getHeaderNames())
2. We iterate over those names (enum) to get their values
while(enum.hasMoreElements())
{
st=(String) enum.nextElement();
out.println(st+" : "+request.getHeader(st));
}

29
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX

Example 3: Parameter capture by name. The


form
Example location: introapweb/examples/ex3.3
This example will be deployed at chapter 5 (De-
ployment). See example 5.1

<html>
<h1><b>Pactador automatic </b></h1>
<form action="http://localhost:8080/josepma/param"
method="get">
<b>Nom o pseudonim:</b>
<input name="nom" type="text" size=50>
<p>
<b>Pacte preferit (selecciona almenys 2 opcions):</b>
<input name="pacte" type="checkbox" value="psc">
PSC
<input name="pacte" type="checkbox" value="ciu">
CiU
<input name="pacte" type="checkbox" value="erc">
ERC
<input name="pacte" type="checkbox" value="icv">
ICV
<p> <p>
<input type="submit" value="Enviar"></textarea>
<input type="reset" value="Reiniciar"></textarea>
</form>
</html>

30
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX

Example 3: Parameter capture by name. The


servlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.util.*;

public class Parameter extends HttpServlet {


private static final String PAGE_TOP=
"<html>"+
"<head>"+
"<title>Parameter capture in an http request</title>"+
"</head>"+
"<body bgcolor=\"white\">"+
"<h1> Parameter capture in an http request </h1>"+
"<pre>"
;

private static final String PAGE_BOTTOM=


" </pre>" +
" </body>"+
" </html>"
;
....(cont)

31
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException {
doPost( request, response ) ;
}
....(cont)

32
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX

public void doPost (HttpServletRequest request,


HttpServletResponse response) {
String[] partits;
Enumeration enum;
String st=new String();
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println (PAGE_TOP);
out.println("<b>Capture of the parameter names:</b>"
+"<br><br>");
enum=request.getParameterNames();
while(enum.hasMoreElements())
{
st=(String) enum.nextElement();
out.println("name="+st);
}
out.println("<b>Capture of the parameter values:"+
"</b><br><br>");
out.println("Parameter name= ’nom’----> Value="+
request.getParameter("nom"));
out.println("Parameter name= ’pacte’----> Values=");
partits=request.getParameterValues("pacte");
for(int i=0;i<partits.length;i++){
out.println("partit "+i+": "+partits[i]);
}
} catch (Exception ex) { ex.printStackTrace();}
}}

33
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX

Example 3: Parameter capture by name.


Remarks
• The action associated to the form is the servlet URI:

<form action="http://localhost:8080/josepma/param">

The way to map a servlet class (Parameter.class) with


a specific URI:
http://localhost:8080/josepma/param)
is presented in sections 2.4 and 2.5

• Parameters may have a collection of values (e.g.,


pacte).Notice the way in which we access all the values
of that parameter:

partits=request.getParameterValues("pacte");
for(int i=0;i<partits.length;i++){
out.println("partit "+i+": "+partits[i]);
}

34
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX

Compilation and execution of a servlet

This is presented in chapter 5

35
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

JSP pages. Difficulties with servlets

A servlet manages the creation of a web page through its


output stream in a way which is non-intuitive and difficult to
generate and to maintain:

• Both the static and the dynamic elements of the web page
are managed by the same code
Static elements: Those elements that do not change in
the resulting page through different requests (e.g., page
headers and footers, table structure...)
Dynamic elements: Those elements that depends on the
parameters of the request and may change in different
requests (e.g., table contents)

• Page contents are generated by means of calls to usual


output methods (e.g., println....), which are combined
with other programming instructions. The structure of the
resulting page is obscure.

• Each servlet is a complete class with several methods and


a complex lifecycle.

36
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

JSP pages. A solution

Idea:
Do not program servlets directly, but a JSP web page

What is a JSP web page


It is a usual web page written in html that incorporates
some dynamic elements (e.g., java expressions, java code,
tag actions and java beans).

• A JSP page is translated automatically into a servlet.

• When the JSP page is requested, the servlet associated to


it is executed.

• The result of the execution of that servlet is an html page


that contains:
– The static (html) code of the JSP page
– The result of the execution of the java expressions and
code of its dynamic part

• JSP pages are executed within a JSP container.


TOMCAT is a servlet and JSP container

37
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

JSP pages. How do they work

hello.jsp

is there a servlet for


hello.jsp?
NO YES

is the servlet
Translate into a servlet more recent than
hello.jsp−−> hello_jsp.java hello.jsp?
NO

Compile YES
hello_jsp.java−−>
hello_jsp.class

Create an object obj NO is there already


of the class an object obj of
hello_jsp.class hello_jsp.class?

YES
send the request to
obj

38
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

The first JSP page

<%@ page import="java.io.*,java.text.*,java.util.*"%>

<HTML>
<head>
<title> First JSP page </title>

</head>

<body>
<h3> First JSP page </h3>

<p>Hello......
<p>1+2=
<%
int p;
p=1+2;
%>
<%=p%>

</body>
</html>

39
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Servlets. Advanced topics

• Filters

• Event listeners

• Servlets and concurrency

Important:
You can skip these sections in a first reading.

In order to understand them you should be familiar with


web application deployment, sessions and scopes.

40
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Filters

Sorry, ongoing work.....

See:

• http://java.sun.com/products/servlet/Filters.html

• i18n module of these notes provide an example that uses


filters

41
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Event listeners

Event listeners are Java classes that manage events that


take place during the web application execution

These events may concern

• To the web application itself


These events are called application-level events or serv-
let context-level events
(Recall that a single servlet context is associated with each
application)
Examples of these sort of events:
– The application has started and is ready to receive
requests
– The application is about to be undeployed and therefore
its ServletContext is about to be destroyed
– One attribute associated to the application level has
been added/modified/removed
(e.g, set/getAttribute(...))

42
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

• To one session that is executed within the web appli-


cation
These events are called HttpSession events
(Sessions are presented in ****)
Examples of these sort of events:
– A specific session has started
– A session has been cancelled or has expired
– One attribute associated to the session level has been
added/modified/removed

In which cases can be useful to manage events associa-


ted to sessions or the own application?

Examples:

• Annotate log information


Duration of a session, number of sessions that have been
initiated in a day, user counter...

• Create a database connection when the application is


deployed, so that it can be shared by all the servlets of
the application and destroy it when the application is shut
down

43
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Notice that the events of each category (Application or


HttpSession) may have two different origins:

• A life cycle event


Examples: a session has initiated/expired; an application
has started/is about to be shutdown

• An attribute event
Examples: A session/application attribute has been crea-
ted/modified/removed

44
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

The servlet API provides interfaces with methods to manage each one of the four
types of events:
ServletContext events HttpSession events
life-cycle evts intfc: ServletContextListener intfc: HttpSessionListener
mthd: contextDestroyed(), mthd: sessionCreated(),
mthd: contextInitialized() mthd: sessionDestroyed()
attrib. chge evts intfc: ServletContextAttributeListener intf:HttpSessionAttributeListener
mthd: attributeAdded() mthd: attributeAdded()
mthd: attributeRemoved() mthd: attributeRemoved()
mthd: attributeReplaced() mthd: attributeReplaced()

This table should be read like this:

In order to manage the ServletContext events of kind life-cycle it is necessary to


implement the methods contextDestroyed(...) and contextInitialized(...)
of the interface ServletContextListener

45
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

• When an application is deployed (this is a life-cycle applica-


tion event), if that application contains a class that imple-
ments the interface ServletContextListener, the method
contextInitialized(...) of that class will be executed

• Therefore, in order to manage the event consis-


ting in an application being deployed, the interface
ServletContextListener and, in particular, the method
contextInitialized(..) must be implemented

46
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Which steps should be followed in order to


listen to events?

1. Decide which events you are interested in listen to

2. Implement the corresponding interface/s and its/their met-


hods

3. Register the listener in the web.xml file


This step is important since the servlet container must
create an instance for each listener class that has been
implemented and, in addition, must register these classes
as listeners of the corresponding events

47
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Example

Example location: introapsweb/examples/ex3.4

Goal of the example:

• Gather information about the number of currently active


sessions, the total number of sessions that have been ini-
tiated since the application was deployed and the duration
of each session.

• Log that information

48
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Steps:

1. Decide which events you are interested in listen to


Two counters will be needed:
• totalSessionCounter
To keep the total number of sessions that have been
initiated since the application deployment
• activeSessionCounter
To keep the number sessions that are currently active.
Both counters will be declared as application attributes,
since they need to work throughout the entire life-cycle of
the application.

They will be initialized when the application


starts up (ServletContextListener.contextInitialized)
and will be removed when it is destroyed
(ServletContextListener.contextDestroyed)

These counters will be udpated when sessi-


ons are created and destroyed. Therefore,
HttpSessionListener.sessionCreated and HttpSessionListener.se
should also be implemented

49
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

2. Implement the corresponding interface/s and its/their met-


hods

50
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

public class SessionCounter


implements ServletContextListener, HttpSessionListener
{

ServletContext servletContext;

public SessionCounter()
{}

/* Methods from the ServletContextListener */


public void contextInitialized(ServletContextEvent scevt
{
servletContext = scevt.getServletContext();

servletContext.setAttribute
("totalSessionCounter",new Integer(0)
servletContext.setAttribute
("activeSessionCounter",new Integer(0

public void contextDestroyed(ServletContextEvent scevt)


{

servletContext.removeAttribute("totalSessionCounter")
servletContext.removeAttribute("activeSessionCounter"
}

51
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

/* Methods for the HttpSessionListener */


public void sessionCreated(HttpSessionEvent sevt)
{
Integer totalSessions = ((Integer)servletContext.
getAttribute("totalSessionCounter"));

servletContext.setAttribute("totalSessionCounter",
new Integer(totalSessions.intValue()+1)

Integer activeSessions = ((Integer)servletContext.


getAttribute("activeSessionCounter")
servletContext.setAttribute("activeSessionCounter",
new Integer(activeSessions.intValue()+1)

servletContext.log("SESSION CREATION");

52
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

public void sessionDestroyed(HttpSessionEvent sevt)


{
Integer activeSessions = ((Integer)servletContext.
getAttribute("activeSessionCounter"))
servletContext.setAttribute("activeSessionCounter",
new Integer(activeSessions.intValue()-1

HttpSession session = sevt.getSession();


long start = session.getCreationTime();
long end = session.getLastAccessedTime();

servletContext.log("SESSION DESTRUCTION, Session Duratio


+ (end - start));
}
}

53
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

3. Register the listener in the web.xml file


In the web.xml file, this registration should be added:

<listener>
<listener-class>SessionCounter</listener-class>
</listener>

54
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

Servlets and concurrency

• Instance attributes of a servlet are not concurrent-


safe
Servlets are multithreaded
Each client request is assigned by the servlet container to
a new thread (usually from a pool of threads)
This thread is associated with a reference to an existing
servlet instance
As a result, various concurrent requests to the same serv-
let can be managed by the same servlet instance thus
accessing the same instance attributes

• Resources shared by different (or the same) servlets


are not concurrent-safe
Different servlets or different instances of the same serv-
let may access concurrently to the same resources
Which are these shared resources?
– Static attributes
– Scoped attributes
Servlets may access to attributes defined in the servlet
context or session scopes

55
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

(e.g.: getServletContext.setAttribute("MaxProducts",mp);
)
The servlet context is shared by all the servlets of a
(non-distributed) web application
– Extern resources
Connection to networks or databases

56
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

How to solve this problem

• Make the servlet implement the SingleThreadModel in-


terface
The servlet container will grant only one thread per
servlet instance. That is: one request per servlet
instance

public class MyServlet extends HttpServlet


implements SingleThreadModel
{...}

However:
– This does not prevent problems that arise from concur-
rent access to static or scoped attributes
– This interface has been deprecated

• Use the Java synchronization mechanisms on the concur-


rently accessed objects
E.g. Use the synchronized element

57
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX

References

• Servlet specification
http://java.sun.com/products/servlet/

• Servlet API
http://java.sun.com/products/servlet/2.2/javadoc/

58

You might also like