Date post: | 27-Dec-2015 |
Category: |
Documents |
Upload: | priscilla-conley |
View: | 252 times |
Download: | 3 times |
Middleware TechnologyServlet
2
Agenda
• Servlet– basic concepts– http servlet– servlet context– communication– between servlets
3
1 Java Servlets
• A servlet is a Java Technology component that executes within the servlet container.
• Typically, servlets perform the following functions:– process the HTTP request– generate the HTTP response dynamically
4
Servlet Container
• A servlet container– is a special JVM (Java Virtual Machine) that is respons
ible for maintaining the life cycle of servlets– must support HTTP as a protocol to exchange requests
and responses– issues threads for each request
5
Servlet Interface
• All servlets either:– implement javax.servlet.Servlet interface, or– extend a class that implements javax.servlet.Servlet
• In the Java Servlet API, classes GenericServlet and HttpServlet implement the Servlet interface.
• HttpServlet is usually extended for Servlet implementation.
6
Servlet Architecture
7
Servlet Life Cycle
• Servlets follow a three-phase life cycle:– 1) initialization– 2) service– 3) destruction
8
Life Cycle: Initialization 1
• A servlet container:– loads a servlet class during startup, or– when the servlet is needed for a request
• After the Servlet class is loaded, the container will instantiate it.
9
Life Cycle: Initialization 2
• Initialization is performed by container before any request can be received.
• Persistent data configuration, heavy resource setup (such as JDBC connection) and any one-time activities should be performed in this state.
• The init() method will be called in this stage with a ServletConfig object as an argument.
10
Life Cycle: ServletConfig Object
• The ServletConfig object allows the servlet to access name-value initialization parameters from the deployment descriptor file using a method such as getInitParameter(String name).
• The object also gives access to the ServletContext object which contains information about the runtime environment.
• ServletContext object is obtained by calling to the getServletContext() method.
11
Life Cycle: Service 1
• The service method is defined for handling client request.
• The Container of a servlet will call this method every time a request for that specific servlet is received.
12
Life Cycle: Service 2
• The Container generally handles concurrent requests with multithreads.
• All interactions with response and requests will occur within this phase until the servlet is destroyed.
13
Life Cycle: Service Method
• The service() method is invoked to every request and is responsible for generating the response to that request.
• The service() method takes two parameters:
– javax.servlet.ServletRequest
– javax.servlet.ServletResponse
public void service ( ServletRequest request, ServletResponse response ) throws IOException {. . .}
14
Life Cycle: Destruction
• When the servlet container determines that the servlet should be removed, it calls the destroy method of the servlet.
• The servlet container waits until all threads running in the service method have been completed or time out before calling the destroy method.
15
HTTPServlet
• A general servlet knows nothing about the HyperText Transfer Protocol (HTTP), which is the major protocol used for Internet.
• A special kind of servlet, HTTPServlet, is needed to handle requests from HTTP clients such as web browsers.
• HTTPServlet is included in the package javax.servlet.http as a subclass of GenericServlet.
16
Hypertext Transfer Protocol
• Hypertext Transfer Protocol (HTTP) is the network protocol that underpins the World Wide Web.
• For example:– a) when a user enters a URL in a Web browser, the browser
issues an HTTP GET request to the Web server
– b) the HTTP GET method is used by the server to retrieve a document
– c) the Web server then responds with the requested HTML document
17
HTTP Methods
Useful for Web applications:
• GET - request information from a server
• POST - sends an unlimited amount of information over a socket connection as part of the HTTP request
Not useful for Web applications:
• PUT - place documents directly to a server
• TRACE - debugging• DELETE - remove documents
from a server• OPTIONS - ask a server what
methods and other options the server supports for the requested resource
• HEAD - requests the header of a response
18
Get Versus Post
• GET request :
• provides a limited amount of information in the form of a query string which is normally up to 255 characters
• visible in a URL must only be used to execute queries in a Web application
• POST request :
• sends an unlimited amount of information
• does not appear as part of a URL
• able to upload data in a Web application
19
HTTP Request
• A valid HTTP request may look like this:– GET /index.html HTTP/1.0
• GET is a method defined by HTTP to ask a server for a specific resource
• /index.html is the resource being requested from the server
• HTTP/1.0 is the version of HTTP being used
20
Handling HTTP Requests
• A Web container processes HTTP requests by executing the service method on an HttpServlet object.
21
Dispatching HTTP Requests
• In the HttpServlet class, the service method dispatches requests to corresponding methods based on the HTTP method such as Get or Post.
• A servlet should extend the HttpServlet class and overrides the doGet() and/or doPost() methods.
22
HTTP Response
• After a request is handled, information should be send back to the client.
• In the HTTP protocol, an HTTP server takes a request from a client and generates a response consisting of– a) a response line– b) headers– c) a body
• The response line contains the HTTP version of the server, a response code and a reason phrase :– HTTP/1.1 200 OK
23
HttpServlet Response
• The HttpServletResponse object is responsible for sending information back to a client.
• An output stream can be obtained by calls to:– 1)getWriter()
– 2)getOutputStream()
PrintWriter out = response.getWriter();out.println("<html>");out.println("<head>");out.println("<title>Hello World!</title>");
24
Task: HTTP Servlet
• Create and deploy a HelloWorld HTTP servlet executing the Get method.– Declare the package – com.examples– Import the required clases:
• import javax.servlet.http.HttpServlet;
• import javax.servlet.http.HttpServletRequest;
• import javax.servlet.http.HttpServletResponse;
• import java.io.PrintWriter;
• import java.io.IOException;
25
Task: HTTP Servlet
public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); //Generate the HTML response out.println(“<HTML>”); out.println(“<HEAD>”); out.println(“<TITLE>Hello Servlet</TITLE>”); out.println(“</HEAD>”); out.println(“<BODY BGCOLOR=’white’>”); out.println(“<B>Hello, World</B>”); out.println(“</BODY>”); out.println(“</HTML>”); out.close(); }}
26
Deployment of an HTTP Servlet
• The HTTPServlet object has to be deployed in the Web server before being used by the server.
• A typical structure for deploying a servlet may look as follows:
27
Deployment Descriptor
• In order to deploy a servlet, we also need to put a deployment descriptor file, web.xml, under the directory of the WEB-INF directory.
• Within the web.xml file, the definition of the servlet is contained:– Define a specific servlet
– Map to a URL pattern
<servlet> <servlet-name>name</servlet-name> <servlet-class>full_class_name</servletclass></servlet>
<servlet-mapping> <servlet-name>name</servlet-name> <url-pattern>pattern</url-pattern></servlet-mapping>
28
URL Patterns
• There are four types of URL patterns:– Exact match:
• <url-pattern>/dir1/dir2/name</url-pattern>– Path match:
• <url-pattern>/dir1/dir2/*</url-pattern>– Extension match:
• <url-pattern>*.ext</url-pattern>– Default resource:
• <url-pattern>/</url-pattern>
29
Mapping Rules 1
• When a request is received, the mapping used will be the first servlet mapping that matches the request's path according to the following rules:
– If the request path exactly matches the mapping, that mapping is used.
– If the request path starts with one or more prefix mappings (not counting the mapping's trailing "/*"), then the longest matching prefix mapping is used.
– For example, "/foo/*" will match "/foo", "/foo/", and "/foo/bar", but not "/foobar".
30
Mapping Rules 2
– If the request path ends with a given extension mapping, it will be forwarded to the specified servlet.
– If none of the previous rules produce a match, the default mapping is used.
31
Deploying HTTP Servlet
• Deploy an HTTP Servlet in Tomcat server.
– Create a directory for deployment. This directory, say "examples", should be put under <Tomcat_Home>/webapps.
32
Deploying HTTP Servlet
• Refer to the directory structure in previous slide, copy the servlet package to the directory WEB-INF/classes.
• Create a web.xml file, if one does not exist, in the directory WEB-INF.
• Test the output of the servlet by entering the URL in the browser: http://localhost/examples/HelloWorld
<web-app xmlns=http://java.sun.com/xml/ns/j2ee version="2.4"> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>com.web.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping></web-app>
33
Task: Deploying HTTP Servlet
• Change the URL address of the servlet to:– http://localhost/examples/myservelt/HelloWorld
• Change the URL address of the servlet to:– http://localhost/examples/Hello
• Deploy the servlet in a different context, say admin. The URL may look like this:– http://localhost/admin/HelloWorld
34
Request Parameter
• Data transmitted from a browser to a servlet is considered the request parameter.
• A Web browser can transmit data to a Web server through HTML form.
• For example, if the submit button of the following form is pressed, the corresponding data is sent to the Web server:
Get /servlet/myForm?name=Bryan HTTP/1.0. . .
35
POST Method
• By using a POST method, data may be contained in the body of the HTTP request:
POST /register HTTP/1.0. . .Accept-Charset: iso-8859-1,*,utf-8Content-type: application/x-www-form-urlencodedContent-length: 129name=Bryan
• The HTTP POST method can only be activated from a form.
36
Extracting Request Parameters
• Request parameters are stored as a set of name-value pairs.
• ServletRequest interface provides the following methods to access the parameters:– getParameter(String name)– getParameterValues(String name)– getParameterNames()– getParameterMap()
37
Extract Parameter
• Parameter value is sent to a servlet through an HTML form. Create a HTTP servlet to retrieve the value of the parameter.
– Put the following HTML file in the examples folder of your web application, name it form.html and browse it.
<html><BODY BGCOLOR=‘white’><B>Submit this Form</B><FORM ACTION=‘/examples/myForm’ METHOD=‘POST’>Name: <INPUT TYPE=‘text’ NAME=‘name’><BR><BR><INPUT TYPE=’submit’></FORM></BODY></html>
38
Extract Parameter
– Methods of the HttpServletRequest are available for extracting parameters from different HTML forms:
• String getParameter(name) – get a value from a text field• String getParameterValues(name) – get values from a multip
le selection such as a checkbox
– Create a servlet named myForm and deploy it under the examples context. The servlet will extract the parameter “name” and generate an HTML page showing the name in bold type.
• Make sure that your servlet implements the correct method to respond to the request.
39
Defining Initial Parameters
• A servlet can have multiple initial parameters defined in the deployment descriptor (web.xml) as follows:
<servlet> <servlet-name>EnglishHello</servlet-name> <servlet-class>com.web.MultiHelloServlet</servlet-class> <init-param> <param-name>greetingText</param-name> <param-value>Welcome</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param></servlet>
40
Getting Initial Parameter –InitSnoop.java
• There are different ways to obtain servlet initial parameters defined in web.xml. One is to override the init() method, which is defined in the GenericServlet class in your servlet.
• The getInitParameter method of the GenericServlet class provides access to the initialization parameters for the servlet instance.
• In the init() method, a greeting String may be defined as follows:
public void init(){. . .greeting = getInitParameter("greetingText");. . . }
41
Multiple Servlet Definition
• Multiple “servlet definitions” can also be defined in a given servlet class. The following could be added to web.xml along with the previous slide.
<servlet> <servlet-name>ChineseHello</servlet-name> <servlet-class>com.web.MultiHelloServlet</servlet-class> <init-param> <param-name>greetingText</param-name> <param-value> 欢迎你 </param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param></servlet>
42
Request Header
• A servlet can access the headers of an HTTP request with the following methods:– getHeader– getHeaders– getHeaderNames
43
Request Attributes
• Attributes are objects associated with a request. They can be access through the following methods:– getAttribute– getAttributeNames– setAttribute
• An attribute name can be associated with only one value.
44
Reserved Attributes
• The following prefixes are reserved for attribute names and cannot be used:– java.– javax.– sun.– com.sun.
45
Request Path 1
• The request path can be obtained from this method:– getRequestURI()
• The request path is composed of different sections.
• These sections can be obtained through the following methods of the request object :
– getContextPath()• If the context of the servlet is the "default" root of the Web s
erver, this call will return an empty string.• Otherwise, the string will starts with a ' / ' character but not e
nd with a ' / ' character
46
Request Path 2
– getServletPath()
• The mapping which activates this request:
• If the mapping matches with the ' /* ' pattern, returns an empty string
• Otherwise, returns a string starts with a ' / ' character.
Context path: /examplesServlet mapping :Pattern: /lec1/ex1Servlet: exServlet
Request Path: /examples/lec1/ex1ContextPath: /examplesServletPath: /lec1/ex1PathInfo: null
47
Request Path 3
– getPathInfo()• The extra part of the request URI that is not returned by the g
etContextPath or getServletPath method.
• If no extra parts, returns null
• otherwise, returns a string starts with a ' / ' character
Context path: /examplesServlet mapping :Pattern: /lec1/*Servlet: exServlet
Request Path: /examples/lec1/ex/ContextPath: /examplesServletPath: /lec1PathInfo: /ex/
48
Request Path 4
• To sum up:– RequestURI = ContextPath + ServletPath + PathInfo
49
Response Headers
• HttpServletResponse can manipulate the HTTP header of a response with following methods:– addHeader(String name, String value)– addIntHeader(String name, int value)– addDateHeader(String name, long date)– setHeader(String name, String value)– setIntHeader(String name, String value)– setDateHeader(String name, long date)
• For example:– You can make the client's browser cache the common graphic of
your web site as following:response.addHeader("Cache-Control","max-age=3600");
50
Servlet Context
• A ServletContext object is the runtime representation of a Web application.
• A servlet has access to the servlet context object through the getServletContext method of the GenericServlet interface.
• The servlet context object provides:– read-only access to context initialization parameters– read-only access to application-level file resources– read-write access to application-level attributes– write access to the application-level log file
51
Context Initial Parameters 1
• The application-wide servlet context parameters defined in the deployment descriptor (web.xml) can be retrieved through the context object.
<web-app> <context-param> <param-name>admin email</param-name> <param-value>[email protected]</param-value> </context-param>. . .
52
Context Initial Parameters 2
• In order to obtain a context object, the following can be used:
ServletContext context = getServletConfig().getServletContext();
• After having the context object, one can access the context initial parameter like this:
String adminEmail = context.getInitParameter("admin email");
53
Access to File Resources
• The ServletContext object provides read-only access to file resources through the getResourceAsStream method that returns a raw InputStream object.
• After having the servlet context object, one can access the file resources as follows:
String fileName = context.getInitParameter(“fileName”);InputStream is = null;BufferedReader reader = null;try { is = context.getResourceAsStream(fileName); reader = new BufferedReader(new inputStreamReader(is)); . . .
54
Access to Attributes 1
• The ServletContext object provides read-write access to runtime context attributes through the getAttribute and setAttribute methods.
• Setting attributes:
ProductList catalog = new ProductList();catalog.add(new Product(“p1”,10);catalog.add(new Product (“p2”,50);context.setAttribute(“catalog”, catalog);
55
Access to Attributes 2
• Getting attributes:
catalog = (ProductList) context.getAttribute(“catalog”);Iterator items = catalog.getProducts();while ( items.hasNext() ) { Product p = (Product) items.next(); out.println(“<TR>”); out.println(“<TD>” + p.getProductCode() + “</TD>”); out.println(“ <TD>” + p.getPrice() + “</TD>”); out.println(“</TR>”);}
56
Write Access to the Log File
• The ServletContext object provides write access to log file through the log method.
• The code may look as follows:– context.log (“This is a log record”);
57
Servlet Communication
• When building a Web application, resource-sharing and communication between servlets are important.
• This can be achieved through one of the following:– servlet context– request dispatching– session tracking– event listening
58
ServletContext
• Servlets can access other servlets within the same servlet context through an instance of :– javax.servlet.ServletContext
• The ServletContext object can be obtained from the ServletConfig object by calling the getServletContext method.
• A list of all other servlets in a given servlet context can be obtained by calling the getServletNames method on the ServletContext object.
59
Accessing a Servlet
• The following code snippet shows how to access another servlet through the servlet context instance.
...
BookDBServlet database = (BookDBServlet)
getServletConfig().getServletContext().getServlet("bookdb");
//Obtain a Servlet and call its public method
// directly
BookDetails bd = database.getBookDetails(bookId);
...
}
}
60
Request Dispatching 1
• A request may need several servlets to cooperate:
• RequestDispatcher object can be used for redirecting a request from one servlet to another.
• An object implementing the RequestDispather interface may be obtained from the ServletContext via the following methods:– getRequestDispatcher– getNamedDispatcher
61
Request Dispatching 2
• The getRequestDispatcher method takes a string argument as the path for the located resources.
• pathname must begin with a "/" and is interpreted as relative to the current context root.
• The required servlet is obtained and returned as a RequestDispatcher object.
62
Request Dispatching 3
• The getNamedDispatcher method takes a string argument indicating the name of a servlet known to the ServletContext.
• Servlets may be given names via server administration or via a web application deployment descriptor.
• A servlet instance can be determined through its name by calling ServletConfig.getServletName()
• If a servlet is known to the ServletContext by name, it is wrapped with a RequestDispatcher object and returned.
63
Example: Request Dispatching
• Note:– The RequestDispatcher object’s include() method dispatches the
request to the “response” servlet path (/response – in the URL mapping).
. . .RequestDispatcher dispatcher =getServletContext().getRequestDispatcher("/response");if (dispatcher != null) { dispatcher.include(request, response);}
64
Using a RequestDispatcher
• To use a request dispatcher, a developer needs to call either the include or forward methods of the RequestDispatcher interface as follows:
. . .dispatcher.include(request, response);. . .
65
Include Method
• The include method of the RequestDispatcher interface may be called at any time.
• It works like a programmatic server-side include and includes the response from the given resource ( Servlet, JSP page or HTML page ) within the caller response.
• The included servlet cannot set headers or call any method that affects the headers of the response. Any attempt to do so should be ignored.
66
Forward Method
• The forward method of the RequestDispatcher interface may only be called by the calling servlet if no output has been committed to the client.
• If output exists in the response buffer that has not been committed, it must be reset (clearing the buffer) before the target Servlet’s service method is called.
• If the response has been committed, an IllegalStateException must be thrown.
67
Request Dispatcher Example 1
// Create a servlet which dispatches its request to another servlet
// using both the forward and include methods of the ServletContext.
//TestDispatherServlet1 as follows:
package com.web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestDispatcherServlet1 extends HttpServlet {
private static final String forwardTo = "/DispatcherServlet2";
68
Request Dispatcher Example 2
private static final String includeIn = "/DispatcherServlet2"; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.print("<html><head>"); out.print("</head><body>"); // Displaying Form out.print("<form action=\""); out.print( req.getRequestURI() ); out.print("\" method=\"post\">"); out.print("<input type=\"hidden\" name=\"mode\" "); out.print("value=\"forward\">"); out.print("<input type=\"submit\" value=\" \""); out.print("> "); out.print(" Forward to another Servlet .."); out.print("</form>");
69
Request Dispatcher Example 3
out.print("<form action=\""); out.print( req.getRequestURI() ); out.print("\" method=\"post\">"); out.print("<input type=\"hidden\" name=\"mode\" "); out.print("value=\"include\">"); out.print("<input type=\"submit\" "); out.print("value=\" \"> "); out.print(" Include another Servlet .."); out.print("</form>"); out.print("</body></html>"); out.close();}
70
Request Dispatcher Example 4
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); String mode = req.getParameter("mode"); PrintWriter out = res.getWriter(); out.print( "Begin...<br>"); // Forwarding to Servlet2 if(mode != null && mode.equals("forward")) { req.setAttribute("mode", "Forwarding Response.."); req.getRequestDispatcher(forwardTo).forward(req, res); } // Including response from Servlet2 if(mode != null && mode.equals("include")) { req.setAttribute("mode", "Including Response.."); req.getRequestDispatcher(includeIn).include(req, res); } }}
71
Request Dispatcher Example 5
• Map the servlet at "/DispatcherServlet1" in the web.xml file
• Create another servlet as the target servlet.
• Make sure the servlet is mapped correctly in the web.xml file.
<servlet> <servlet-name>DispatcherServlet2</servlet-name> <servlet-class>com.web.TestDispatcherServlet2</servlet-class></servlet><servlet-mapping> <servlet-name>DispatcherServlet2</servlet-name> <url-pattern>/DispatcherServlet2</url-pattern></servlet-mapping>
72
Request Dispatcher
• What is the difference between include and forward methods?
73
Session Tacking
• HTTP is a stateless protocol and associating requests with a particular client is difficult.
• Session tracking mechanism is used to maintain state about a series of requests from the same user.
• javax.servlet.http.HttpSession defined in Servlet specification allows a servlet containers to use different approaches to track a user's session easily.
74
HttpSession
• HttpSession is defined in the Servlet specification for managing the state of a client.
• Each HttpSession instance is associated with an ID and can store the client's data.
• The stored data will be kept privately until the client's session is destroyed.
• SessionTracker.java
75
Obtaining a Session
• Servlets do not create sessions by default.• getSession method of the HttpServletRequest object has t
o be called explicitly to obtain a user’s session.
public class CatalogServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session HttpSession session = request.getSession(); ... }}
76
HttpSession Attributes
• Objects, or data, can be bound to a session as attributes.
• The following methods can be used to manipulate the attributes:– void setAttribute(String name, Object value)
• binds an object to this session, using the name specified– Object getAttribute(String name)
• returns the object bound with the specified name in this session, or null if no object is bound under the name
– Enumeration getAttributeNames()• returns an Enumeration of String objects containing the name
s of all objects bound to this session– void removeAttribute(String name)
• removes the object with the specified name from this session
77
Invalidating the Session
• A user's session can be invalidated manually or automatically when the session timeouts.
• To manually invalidate a session, the session's invalidate () method can be used:
. . .HttpSession session = request.getSession();. . .// After the process, invalidate the session and clear// the datasession.invalidate();. . .
78
Cookies
• Cookies are used to provide session ID and can be used to store information shared by the client and server.
• When a session is created, an HTTP header, Set-Cookie, will be sent to the client. This cookie stores the session ID in the client until time-out.
• The ID may looks like:
Set-Cookie:JSESSIONID=50BAB1DB58D45F833D78D9EC1C5A10C5
• This ID will be stored in a client and passed back to the server for each subsequent request.
Cookie: JSESSIONID=50BAB1DB58D45F833D78D9EC1C5A10C5
79
Cookie Object
• Other than providing session ID, cookie can be used to store information shared by both the client and server.
• javax.servlet.http.Cookie class provides methods for manipulating the information such as:– setValue(String value)– getValue()– setComment(String comment)– getComment()– setMaxAge(int second)– getMaxAge()– . . .
80
Using Cookies
• A procedure for using cookies to store information in a client usually includes:– instantiating a cookie object– setting any attributes– sending the cookie
81
Instantiating a Cookie Object
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String bookId = request.getParameter("Buy");
if (bookId != null) {
Cookie Book = new Cookie("book_purchased",bookId);
...
}
}
82
Setting Attributes
. . .Cookie Book = new Cookie("book_purchased",bookId); Book.setComment ("Book sold" );. . .}
83
Sending a Cookie
. . .
Cookie Book = new Cookie("book_purchased",bookId);
Book.setComment ("Book sold" );
response.addCookie(Book);
. . .
}
84
Retrieving Information
• A procedure to retrieve information from a cookie:– retrieve all cookies from the user's request– find the cookie or cookies with specific names– get the values of the cookies found
85
Retrieving a Cookie 1
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... String bookId = request.getParameter("Remove"); ... if (bookId != null) { // Find the cookie that pertains to that book Cookie[] cookies = request.getCookies();
86
Retrieving a Cookie 2
for(i=0; i < cookies.length; i++) { Cookie thisCookie = cookie[i]; if (thisCookie.getName().equals("book_purchased") && thisCookie.getValue().equals(bookId)) {
// Delete the cookie by setting its // maximum age to zero thisCookie.setMaxAge(0); response.addCookie(thisCookie); }
87
Your Task
• Create a servlet that stores the last time the client visits this servlet within the session.
• java.util.Date could be used to obtain the time-stamp.• The time-stamp should be stored as a cookie.• A message similar to the following should be shown:
– Your last visit time is Fri Apr 01 14:37:48 CST2007
88
URL Rewriting
• If a client does not support cookies, URL rewriting could be used as a mechanism for session tracking.
• While using this method, session ID is added to the URL of each page generated.
• For example, after a session ID 123456 is generated, the rewritten URL might look like:– http://localhost/ServletTest/index.html;jsessionid=123456
89
Methods for URL Rewriting
• The HttpServletResponse object provides methods for appending a session ID to a URL address string:
– String encodeURL(java.lang.String url)
• Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
– String encodeRedirectURL(String url)
• Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
90
Investigate the usage of URL rewriting (homework)
• Create a servlet, named "URLRewrite", which shows the following information on a web page:– request URL (request.getURL())
– request URI (request.getURI())
– servlet path (request.getServletPath() )
– path info (request.getPathInfo() )
– session id ( request.getSession().getId()
– a hyperlink pointing to another servlet named "DisplayURL"
• Create a servlet DisplayURL which shows the session id.
91
Investigate the usage of URL rewriting (homework)
• Make sure that the browser accepts cookies.• Browse the URLRewrite servlet and click on the link to th
e DisplayURL servlet. What is the session id displayed on both page?
• Configure the browser to disable the cookies.• Repeat step d and observe the result.• Modify the URLRewrite servlet and call the response.enc
odeURL method to modify the hyperlink pointing to theDisplayURL servlet.
• What is the result now and what is the conclusion?
92
Servlet Event Listener
• Information about container-managed life cycle events, such as initialization of a web application or loading of a database could be useful.
• Servlet event listener provides a mechanism to obtain these information.
93
Event Listener Interfaces
• Interfaces of different event listeners:
• javax.servlet.ServletRequestListener
• javax.servlet.ServletRequestAttributeListener
• javax.servlet.ServletContextListener
• javax.servlet.ServletContextAttributeListener
• javax.servlet.http.HttpSessionListener
• javax.servlet.http.HttpSessionAttributeListener
94
Example of a Listener
• A listener can be used in different situations and here is one of the examples:
– When a web application starts up, the listener class is notified by the container and prepares the connection to the database.
– When the application is closed and removed from the web server, the listener class is notified and the database connection is closed.
95
Servlet Event Listener (Homework)
• Create HttpSessionListener which counts the number of users connected to the server concurrently.– Create a class named UserCounter which implements the HttpSe
ssionListener.
– Define a static integer variable "counter" for counting the users.
– Find out which methods are needed to implement the HttpSessionListener interface.
– Within which method should you add or deduct the number of users?
– Provide a static method getUserCounted to return the number of users connecting currently.
96
Servlet Event Listener (Homework)
• Deploy the listener developed– Modify the web.xml file as follows to deploy the listener:
<listener><listener-class>FULL_CLASS_NAME_OF_THE_LISTENER</listener-class></listener>
• Create a servlet DisplayUser which displays the number of connected user by calling the getUserCount method of the UserCounter class.
• What can be observed when establishing more connections to the DisplayUser servlet?
97
Servlet Summary 1
• The most commonly used servlet extends the HttpServlet class.
• The life cycle of a servlet include initialization, service and destruction.
• The web container dispatches the requests to the corresponding methods according to their types such as Get or Post.
• The URL of a servlet could be mapped as part of the web.xml file.
98
Servlet Summary 2
• Data transmitted from a browser to a servlet is considered a request parameter.
• ServletRequest interface provides methods such as getParameter() for accessing the request parameters.
• Initial parameters for a servlet could be assigned in the web.xml file and extracted within the init() method of a servlet using the getInitParameter method.
• HttpServletRequest interface also provides methods for accessing different attributes of an HTTP request such as header, URI, etc.
99
Servlet Summary 3
• ServletContext object is the runtime representation of a web application.
• The servlet context object provides:– a) read-only access to context initialization parameters– b) read-only access to application-level file resources– c) read-write access to application-level attributes– d) write access to the application-level log file
100
Servlet Summary 4
• Information and resources can be shared between servlets and the container.
• Different approaches could be used:– servlet context– request dispatching– session tracking– event listening