2.8. Session Management: Juan M. Gimeno, Josep M. Rib o January, 2008
2.8. Session Management: Juan M. Gimeno, Josep M. Rib o January, 2008
Session management
Juan M. Gimeno, Josep M. Rib o January, 2008
INDEX
Sessions. Motivation
INDEX
Both examples involve a conversation between the customer and the web application (at the server side). The server must maintain, at every moment, the clients conversational state (i.e., the information that the client has sent to the server along his/her interaction with the web application) How to remember the clients conversational state using a stateless protocol?
2
Sessions. Motivation
INDEX
In a web application we may maintain the client state by means of dierent techniques Hidden elds URL rewriting Cookies Servlet and JSP API
INDEX
Hidden elds
Idea: The client state is passed from the server to the client and back to the server in a hidden eld of a form
<% int n; if (request.getParameter("counter")==null) n=1; else{ n=Integer.parseInt(request.getParameter("counter"))+1; } %> <html> <h1>Page counter using hidden fields</h1> <form action="index.jsp" method="get" > This is your access number <%=n%> <p> <input type="hidden" name="counter" value=<%=String.valueOf(n)%>> <input type="submit" value="New access"> </form> </html>
INDEX
URL rewriting
Idea: The client state is passed from the server to the client and back to the server in the query string, accompanying the URL
<% int n; if (request.getParameter("counter")==null) n=1; else{ n=Integer.parseInt(request.getParameter("counter"))+1; } %> <html> <h1>Page counter using URL rewriting</h1> This is your access number <%=n%> <p> <a href="index.jsp?counter=<%=String.valueOf(n)%>"> New access</a> </html>
Sessions. Cookies
INDEX
Cookies
A cookie is a pair (key-string,value-string) which is: Sent by the server to the client as a part of the response to a client request, Stored by the client browser (when it receives the cookie from the server) and Sent back by the client as a part of subsequent requests to the same server
Sessions. Cookies
INDEX
Cookies (2)
Cookies can be used to store the state reached by the client in the previous request so that it can be restored in the next one
Example: The cookie (accessNb,12) may mean that as a consequence of the last request (acces to a page p) the number of accesses to p has been 12 When the client sends another reques to access p the server will increase that number by one and will send the new cookie (accessNb,13) to the client
Sessions. Cookies
INDEX
Cookies features
Cookies are stored in the client browser as pairs (string-key, string-value). Each pair is associated to a URL domain Cookies have an expiration date. After that date, the client state will be lost Cookies are not a universal way to store the client state (e.g., the client may disable cookies) Cookies are usually used in two situations: Remmember client preferences (e.g., client language) Support to session management (see below)
Sessions. Cookies
INDEX
Cookies. API
Java provides support for cookies. In particular: It denes the class Cookie It provides operations to get the cookies from the client request (request.getCookies()) and to add cookies to the server response (response.addCookie(...))
Sessions. Cookies
INDEX
10
Sessions. Cookies
INDEX
Interface HttpServletRequest Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. Interface HttpServletResponse void addCookie(Cookie cookie) Adds the specied cookie to the response.
11
Sessions. Cookies
INDEX
12
Sessions. Cookies
INDEX
...........continuation
<html> <h2> Access counter </h2> <p> This is a version without session support. A cookie is used to store (in the client side) the value of the last access number <p> <p> This is your access number <%=n%> <p> Click <a href="index.jsp"> here </a> </html>
13
INDEX
Idea of sessions: 1. The client sends a request to the server 2. The server creates a session which will encompass all the interactions with that client in the next few minutes. This session is identied with a session identier 3. The server manages the client request and elaborates a response to its request. 4. This management may remember some objects which will be retrieved by later requests of the same session. These remembered objects: are called attributes are associated to the session can be retrieved using a key (string)
14
INDEX
5. When the server has nished managing the request, the server sends to the client: its response (html/xml code) a cookie with the session identier (sid) 6. When the client sends another request to the same server, it includes the cookie (with the identier sid) that received from it. In this way the server can identify the session. 7. The server manages the new request. In particular, it may retrieve the session attributes which were set in the last session access.
15
INDEX
CLIENT
httprequest: "counter.jsp"
SERVER
counter_jsp.class is executed: *Create a session identifier (sid) *Create a cookie JSESSIONID=sid *Add the cookie to the server response *Manage the request and set session attributes: session.setAttribute("counter",new Integer(1));
counter_jsp.class is executed: *Get the session identifier obtained from the request (sid): session=request.getSession(); *Manage the session: Get/Set session attributes: session.getAttribute("counter");
16
INDEX
The following classes and interfaces are provided by the Servlet and JSP API in order to manage sessions: HttpSession HttpServletRequest HttpServletResponse Cookie In order to trace objects that are incorporated and/or removed from a session or activation/remove of the own session, the API oers the following classes and interfaces (however, these classes are not presented in these slides): HttpSessionActivationListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionBindingListener, HttpSessionBindingEvent, HttpSessionEvent
17
INDEX
A servlet/JSP page which manages a request which needs session support must do the following: 1. Session creation/identication Identify an already created session which can be associated to that request (or create a session for that request if none existed) 2. Attribute management Manage session attributes (get/set attributes associated to that session) 3. Session tracking Ensure that the client knows the session identier so that later requests from the same client may be associated (by the server) to the same session 4. Session destruction
18
INDEX
Session creation/identication
A client wants to interact with a server (e.g., the client wants to make a reservation in an theatre reservation web application). The client requires session management When the client calls the rst servlet/JSP page of the application, the server must create the session. When the client calls a posterior servlet/JSP page (after the session creation), the server must retrieve the session that was created previously. This session is attached to the client request by means of a cookie (or a parameter in the query string) that contains the session identier How is this done? In the following slides we will see it both for servlets and JSP pages
19
INDEX
The method service(request, response)/doGet(request, response)/doPost(request, response) should incorporate the following sentence: HttpSession session=request.getSession(); Creates a session (with a new identier) if request does not contain any session identier. Otherwise, it retrieves the session identier attached to request (by means of a cookie or a parameter in a query string) and uses it to build an object of class HttpSession HttpSession session=request.getSession(create); If create=true, the same as before If create=false, retrieves an already existing session but it does not create a new one if request does not have any session identier attached to
20
INDEX
JSP pages that need session management should use the page directive <%@ page session="true" %> If this directive is used, then
A JSP page can refer to the session which is associated to it by means of the implicit variable session
21
INDEX
22
INDEX
INDEX
pageContext is an object that encapsulates the page context, which includes the following aspects associated to the JSP page: The request that has launched this JSP page That is, the rst parameter of jspService. It can be retrieved by:
request=pageContext.getRequest();
The pending response which will be generated as a result of the execution of this JSP page and, afterwards, sent to the client
response=pageContext.getResponse();
24
INDEX
The output stream that has been associated to this JSP page
out=pageContext.getOut();
The session that is associated to this request getPageContext(...) calls request.getSession() The session can be retrieved by:
session = pageContext.getSession();
The application to which this JSP page is associated (useful to dene application objects. See below)
application = pageContext.getServletContext();
25
INDEX
Therefore the JSP page can refer to the session which has been associated to it by means of the implicit variable session.
26
INDEX
Attribute management
Servlets and JSP pages may remember several objects across dierent requests within the same session Remembering an object This is done by associating the object which is to be remembered to an attribute name (a key string) In turn, this attribute name will be associated to the session
ObjectClass object=new Object(...); session.setAttribute("attrName", object);}
Retrieving the object Another request associated to the same session may retrieve the object associated to the attribute called attrName in the following way:
ObjectClass oc= (ObjectClass) session.getAttribute("attrName");
27
INDEX
Some considerations: Only objects can be stored as attributes Primitive types (e.g., int, oat....) must be wrapped using the wrapper classes (e.g., Integer, Float...) Dierent servlets/JSP pages share the same session attributes. Beware of name clash.
28
INDEX
Session tracking
In order to identify and manage the session associated to a request: The server should send the session identier to the client in its response The client should send the session identier (obtained from the server) in subsequent requests This can be done in two dierent ways: 1. By means of a cookie 2. By adding the session identier in the query string of the request
29
INDEX
When a servlet creates a session by means of getSession() or getSession(true) it adds a cookie to the response to be sent to the client In particular, it adds a header to the response with the following code:
Set-Cookie: JSESSIONID=123456789poiuyt
When the client sends subsequent requests to the server, it adds to the request the previous cookie:
Cookie: JSESSIONID=123456789poiuyt
When the servlet executes the operation request.getSession() for a request that contains a cookie JSESSIONID=sessionId, it returns a session with the identier sessionId
30
INDEX
The client may not accept cookies. However, session management should be equally possible, even in this case
Idea: If the client does not accept cookies, include the session identier as a parameter of any subsequent request sent by the client The parameter will be codied as a query string accompanying the URL of the request Example:
<a href="counter.jsp;jsessionid=9898988787xcds8"> link </a>
31
INDEX
This method encodes the url by including the session identier only in the case that this is necessary (client browser does not accept cookies and the servlet requires session management). It returns the encoded url or the url unchanged (if encoding is not necessary)
32
INDEX
The client will receive: If it does not accept cookies and session management is enabled for that JSP page:
<a href="http://ingrid.udl.net:8080/counter.jsp? jsessionid=9898988787xcds8"> link </a>
If it accepts cookies and session management is enabled for that JSP page:
<a href="http://ingrid.udl.net:8080/counter.jsp"> link </a>
33
INDEX
Session destruction
Sessions are automatically cancelled (and their resources deallocated) when they reach a certain timeout This timeout is specied in the conguration le web.xml of the server container. In the case of Tomcat:
<web-app> ... <session-config> <session-timeout> 30 </session-timeout> </session-config> ... </web-app>
In this case, the session timeout is established in 30 minutes It is possible to change the timeout for a specic session using the method setMaxInactiveInterval(n) of the interface HttpSession:
session.setMaxInactiveInterval(300);
This states the timeout for this session to 300 seconds (5 minutes).
34
INDEX
Session destruction
35
INDEX
Warning: This example only works if the cookies are enabled in the client
36
INDEX
This version works both if the client has the cookies enabled or disabled Notice the use of:
<%=response.encodeURL("index.jsp") %>
37
INDEX
public class Counter extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doPost( request, response ) ; }
continues.....
38
INDEX
.......continues
public void doPost (HttpServletRequest request, HttpServletResponse response) { try { response.setContentType ("text/html;charset=ISO-8859-1"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(); //getSession is responsible for including the cookie //JSESSIONID to the response if (session.getAttribute("counter")==null) session.setAttribute("counter", new Integer(1)); int c= ((Integer) session.getAttribute("counter")).intValue();
continues.........
39
INDEX
out.write("\n\n"); out.write("<html>\n\n"); out.write("<h2> Access counter"); out.write("</h2>\n\n"); out.write(" \n\nThis is your access number "); out.print(c); out.write("\n\n"); session.setAttribute("counter",new Integer(c+1)); out.write("\n"); out.write("<p>\nClick \n\n\n"); out.write( "<a href=\"" + "counter\">"+ "here "); out.write("</a>\n\n"); out.write("</html>\n"); if (c>=5) session.invalidate(); } catch (Exception ex) { } } } ex.printStackTrace();
40
INDEX
This example shows a primitive bookstore on-line It uses java beans, session management and JDBC. It is presented in java beans module (ex. ***)
41
INDEX
In JSP pages and servlets it is possible to dene 4 dierent scopes for objects (attributes): Page scope Request scope Session scope Application scope
42
INDEX
Page scope
An object (attribute) associated to a page scope is visible only within the JSP page to which that scope refers The page scope corresponds to the execution of the method jspService of the servlet to which that JSP page is translated Object declaration within the page scope
pageContext.setAttribute ("attrId",object,PageContext.PAGE_SCOPE);
pageContext.setAttribute("attrId",object);
Recall that pageContext is an implicit object that can be used in a JSP page
43
INDEX
Request scope
An object (attribute) associated to a request scope is visible: Within the JSP page to which that http request refers and Within the pages invoked by means of <jsp:include..> or <jsp:forward...> from that page Object declaration within the request scope
pageContext.setAttribute ("attrId",object,PageContext.REQUEST_SCOPE);
request.setAttribute("attrId",object);
Recall that both pageContext and request are implicit objects that can be used in a JSP page
44
INDEX
Session scope
An object (attribute) associated to a session scope is visible within all the requests associated with an HttpSession object with a specic session ID Object declaration within the request scope
pageContext.setAttribute ("attrId",object,PageContext.SESSION_SCOPE);
session.setAttribute("attrId",object);
Recall that both pageContext and session are implicit objects that can be used in a JSP page The session scope is used normally when the following situation occurs: The application maintains a dialogue with the user through dierent http requests and Subsequent requests within the dialogue should remember the state of some application objects stated by previous requests
45
INDEX
Application scope
An object (attribute) associated to an application scope is visible within all the servlets and JSP pages of an application Object declaration within the request scope
pageContext.setAttribute ("attrId",object,PageContext.APPLICATION_SCOPE);
application.setAttribute("attrId",object);
Recall that both pageContext and application are implicit objects that can be used in a JSP page
46
INDEX
Initialization parameters of the application scope It is possible to declare and initialize some constant parameters which should be visible throughout the application This initialization is done in the web.xml deployment descriptor:
<context-param> <param-name>jdbc.driver</param-name> <param-value>jdbc.postgresql</param-value> </context-param> <context-param> <param-name>...</param-name> <param-value>...</param-value> </context-param> ...
47