introduction to web applications with java technology 3

59
Introduction to Web applications with Java Technology 3- Servlets Juan M. Gimeno, Josep M. Rib´ o January, 2008

Upload: khangminh22

Post on 23-Feb-2023

0 views

Category:

Documents


0 download

TRANSCRIPT

Introduction to Web applications withJava Technology

3- Servlets

Juan M. Gimeno, Josep M. Ribo

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 httprequests sent by a client and generate responses tothem.

• An http request from a client may refer (in its URI) aservlet as the requested resource.

• The execution of that servlet will manage the request andgenerate 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, theservlet 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 classto set up the servlet (e.g., create a connexion with adatabase)

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 theclient

5. Invoking the destroy(..) operation of the servlet classto 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 arerequested.

4

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

Servlet API

Java defines a set of packages to work with servlets. Inparticular, 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 mustbe implemented by any servlet class

Usually, this interface is implemented by means of a classthat 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 writean HTTP servlet for use on the Web, extend HttpServletinstead.

• 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 HTTPservlets (i.e., servlets written for the web)

HTTP servlets written by a programmer should subclassifyHttpServlet 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 thatsubclassify HttpServlet. The overriden operations are doGetand 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 subclassifyHttpServlet if the HTTP request sent to that specific servletuses 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 subclassifyHttpServlet if the HTTP request sent to that specific servletuses 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 thedetails about http requests. It controls the access to therequest 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 outputstream 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 webapplication (there is just one context for the whole webapplication)

– In the case of distributed web applications (marked as“distributed” in their deployment descriptors), there willbe a context for each Java virtual machine. In this case,the servlet context cannot store the global informationfor the whole application

– The servlet context for a specific application can beobtained 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 initializationparameter with name name, or null if the parameter doesnot exist

This parameter can be set in the web.xml deploymentdescriptor (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("parameterName");

16

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

Servlet API. ServletConfig

• Outline:

– It is used to send initialization information from theservlet 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 namedinitialization parameter, or null if the parameter doesnot exist.

Servlet initialization parameters can be stated within theservlet definition in the web.xml file:

<servlet><servlet-name>ServletName</servlet-name>

<description>ServletDescription</description><servlet-class>com.alexandria.package.MyServlet</servlet-class><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 ispresented 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 sentby a servlet to a resource

– A specific object of this interface is obtained by a callto:ServletContext.getRequestDispatcher(..)

orrequest.getRequestDispatcher(..)

• Some methods:

– void forward(ServletRequest request, ServletResponse response)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 response)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 tosomeResource. Notice that request is the same requestthat MyServlet has received from the client

Before forwarding it to another resource, it is possible thatdoPost 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 contentsof 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 inPOST 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 codifiedas query string)

• A query string in the body (POST request codified asquery string)

• A sequence of (name, value) pairs linked by a pseudo-random string in the body (POST request codified asmultipart-data)

In this example we do not explore how to get each oneof the parameters by its name, but how to obtain theelements that constitute the request.

Next example will be devoted to the capture of individualparameters 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 bymeans of the method getReader() of the interface Serv-letRequest:

BufferedReader br=request.getReader();

• If the request body were a byte sequence, then it wouldbe necessary to get an input stream (binary) by means ofthe method getInputStream

28

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

• When the request is received, we do not know either howmany headers will come up in the request or the value ofthose headers. Therefore,

1. We get the header names:(enum=request.getHeaderNames())

2. We iterate over those names (enum) to get their valueswhile(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. Theform

Example location: introapweb/examples/ex3.3This 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. Theservlet

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) witha 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 valuesof 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 itsoutput stream in a way which is non-intuitive and difficult togenerate and to maintain:

• Both the static and the dynamic elements of the web pageare managed by the same code

Static elements: Those elements that do not change inthe resulting page through different requests (e.g., pageheaders and footers, table structure...)

Dynamic elements: Those elements that depends on theparameters of the request and may change in differentrequests (e.g., table contents)

• Page contents are generated by means of calls to usualoutput methods (e.g., println....), which are combinedwith other programming instructions. The structure of theresulting page is obscure.

• Each servlet is a complete class with several methods anda 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 pageIt is a usual web page written in html that incorporatessome 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 toit is executed.

• The result of the execution of that servlet is an html pagethat 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

is there a servlet for hello.jsp?

Translate into a servlet

hello.jsp−−>hello_jsp.java

hello_jsp.java−−>hello_jsp.class

Compile

hello_jsp.classof the class

is the servlet more recent thanhello.jsp?

is there already

hello_jsp.class?

Create an object objan object obj of

send the request toobj

hello.jsp

NO YES

YES

NO

NO

YES

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 withweb 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 usesfilters

41

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

Event listeners

Event listeners are Java classes that manage events thattake 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 eachapplication)

Examples of these sort of events:

– The application has started and is ready to receiverequests

– The application is about to be undeployed and thereforeits ServletContext is about to be destroyed

– One attribute associated to the application level hasbeen 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 beeninitiated in a day, user counter...

• Create a database connection when the application isdeployed, so that it can be shared by all the servlets ofthe application and destroy it when the application is shutdown

43

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

Notice that the events of each category (Application orHttpSession) may have two different origins:

• A life cycle event

Examples: a session has initiated/expired; an applicationhas 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 fourtypes of events:

ServletContext events HttpSession events

life-cycle evts intfc: ServletContextListener intfc: HttpSessionListenermthd: contextDestroyed(), mthd: sessionCreated(),

mthd: contextInitialized() mthd: sessionDestroyed()

attrib. chge evts intfc: ServletContextAttributeListener intf:HttpSessionAttributeListenermthd: 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 toimplement 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 methodcontextInitialized(...) of that class will be executed

• Therefore, in order to manage the event consis-ting in an application being deployed, the interfaceServletContextListener and, in particular, the methodcontextInitialized(..) must be implemented

46

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

Which steps should be followed in order tolisten 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 mustcreate an instance for each listener class that has beenimplemented and, in addition, must register these classesas 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 activesessions, the total number of sessions that have been ini-tiated since the application was deployed and the durationof 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:

• totalSessionCounterTo keep the total number of sessions that have beeninitiated since the application deployment

• activeSessionCounterTo 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 ofthe application.

They will be initialized when the applicationstarts 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.sessionDestroyed

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 SessionCounterimplements 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 Duration:"+ (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 toa new thread (usually from a pool of threads)

This thread is associated with a reference to an existingservlet instance

As a result, various concurrent requests to the same serv-let can be managed by the same servlet instance thusaccessing the same instance attributes

• Resources shared by different (or the same) servletsare 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 servletcontext 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 resourcesConnection 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 perservlet instance. That is: one request per servletinstance

public class MyServlet extends HttpServletimplements 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