Home | Java - The Session Tracking API

Chapter: Web or internet Programming : Applets

Java - The Session Tracking API

Using sessions in servlets is straightforward and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions.

The Session Tracking API

 

 

Using sessions in servlets is straightforward and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions. Finally, if you return any URLs to the clients that reference your site and URL-rewriting is being used, you need to attach the session information to the URLs.

 

 

Looking Up the HttpSession Object Associated with the Current Request

 

You look up the HttpSession object by calling the getSession method of HttpServletRequest. Behind the scenes, the system extracts a user ID from a cookie or attached URL data, then uses that as a key into a table of previously created HttpSession objects. But this is all done transparently to the programmer: you just call getSession. If getSession returns null, this means that the user is not already participating in a session, so you can create a new session. Creating a new session in this case is so commonly done that there is an option to automatically create a new session if one doesn’t already exist. Just pass true to getSession. Thus, your first step usually looks like this:

 

HttpSession session = request.getSession(true);

 

 

Looking Up Information Associated with a Session

 

HttpSession objects live on the server; they’re just automatically associated with the client by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a built-in data structure that lets you store any number of keys and associated values. In version 2.1 and earlier of the servlet API, you use session.getValue("attribute") to look up a previously stored value. The return type is Object, so you have to do a typecast to whatever more specific type of data was associated with that attribute name in the session. The return value is null if there is no such attribute, so you need to check for null before calling methods on objects associated with sessions. In version 2.2 of the servlet API, getValue is deprecated in favor of get-Attribute because of the better naming match with setAttribute (in version 2.1 the match for getValue is putValue, not setValue). Nevertheless, since not all commercial servlet engines yet support version 2.2, I’ll use getValue in my examples. Here’s a representative example, assuming ShoppingCart is some class you’ve defined to store information on items being purchased HttpSession session = request.getSession(true);

 

ShoppingCart cart = (ShoppingCart)session.getValue("shoppingCart"); if (cart == null) {

 

// No cart already in session cart = new ShoppingCart();

 

session.putValue("shoppingCart", cart);

 

}

 

doSomethingWith(cart);

 

In most cases, you have a specific attribute name in mind and want to find the value (if any) already associated with that name. However, you can also discover all the attribute names in a given session by calling getValueNames, which returns an array of strings. This method is your only option for finding attribute names in version 2.1, but in servlet engines supporting version 2.2 of the servlet specification, you can use getAttributeNames. That method is more consistent in that it returns an Enumeration, just like the getHeader- Names and getParameterNames methods of HttpServletRequest. Although the data that was explicitly associated with a session is the part you care most about, there are some other pieces of information that are sometimes useful as well. Here is a summary of the methods available in the HttpSession class.

 

public Object getValue(String name)

 

public Object getAttribute(String name)

 

 

These methods extract a previously stored value from a session object. They return null if there is no value associated with the given name. Use getValue in version 2.1 of the servlet API. Version 2.2 supports both methods, but getAttribute is preferred and getValue is deprecated.

 

 

public void putValue(String name, Object value)

 

public void setAttribute(String name, Object value)

 

 

These methods associate a value with a name. Use putValue with version 2.1 servlets and either setAttribute (preferred) or putValue (deprecated) with version 2.2 servlets. If the object supplied to putValue or setAttribute implements the HttpSessionBindingListener interface, the object’s valueBound method is called after it is stored in the session. Similarly, if the previous value implements HttpSessionBindingListener, its valueUnbound method is called.

 

public void removeValue(String name)

 

public void removeAttribute(String name)

 

These methods remove any values associated with the designated name.If the value being removed implements HttpSessionBindingListener, its valueUnbound method is called. With version 2.1 servlets,use removeValue. In version 2.2, removeAttribute is preferred, butremoveValue is still supported (albeit deprecated) for backward compatibility.

 

public String[] getValueNames()

 

public Enumeration getAttributeNames()

 

These methods return the names of all attributes in the session. Use getValueNames in version 2.1 of the servlet specification. In version 2.2, getValueNames is supported but deprecated; use getAttributeNames instead.

 

public String getId()

 

This method returns the unique identifier generated for each session. It is sometimes used as the key name when only a single value is associated with a session, or when information about sessions is being logged.

 

public boolean isNew()

 

This method returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.

 

public long getCreationTime()

 

This method returns the time in milliseconds since midnight, January 1, 1970 (GMT) at which the session was first built. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar.

 

public long getLastAccessedTime()

 

This method returns the time in milliseconds since midnight, January 1, 1970 (GMT) at which the session was last sent from the client.

 

Associating Information with a Session

 

HttpSession session = request.getSession(true);

 

session.putValue("referringPage", request.getHeader("Referer"));

ShoppingCart cart = (ShoppingCart)session.getValue("previousItems"); if (cart == null) {

 

// No cart already in session cart = new ShoppingCart();

 

session.putValue("previousItems", cart);

 

}

 

String itemID = request.getParameter("itemID"); if (itemID != null) {

cart.addItem(Catalog.getItem(itemID));

 

}

 

Terminating Sessions

 

Sessions will automatically become inactive when the amount of time between client accesses exceeds the interval specified by getMaxInactiveInterval. When this happens, any objects bound to the HttpSession object automatically get unbound. When this happens, your attached objects will automatically be notified if they implement the HttpSessionBindingListener interface. Rather than waiting for sessions to time out, you can explicitly deactivate a session through the use of the session’s invalidate method.

 

A Servlet Showing Per-Client Access Counts

 

The following program presents a simple servlet that shows basic information about the client’s session. When the client connects, the servlet uses request.getSession(true) to either retrieve the existing session or, if there was no session, to create a new one. The servlet then looks for an attribute of type Integer called accessCount. If it cannot find such an attribute, it uses 0 as the number of previous accesses. This value is then incremented and associated with the session by putValue. Finally, the servlet prints a small HTML table showing information about the session.

 

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

 

import javax.servlet.http.*; import java.net.*;

import java.util.*;

 

/**

 

*  Simple example of session tracking. See the shopping

 

*  cart example for a more detailed one.

 

*/

 

public class ShowSession extends HttpServlet {

 

 

public void doGet(HttpServletRequest request, HttpServletResponse response)

 

throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example";

HttpSession session = request.getSession(true);

 

String heading;

 

// Use getAttribute instead of getValue in version 2.2.

 

Integer accessCount = (Integer)session.getValue("accessCount"); if (accessCount == null) {

 

accessCount = new Integer(0); heading = "Welcome, Newcomer";

 

} else {

 

heading = "Welcome Back";

 

accessCount = new Integer(accessCount.intValue() + 1);

 

}

 

 

// Use setAttribute instead of putValue in version 2.2. session.putValue("accessCount", accessCount);

 

out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" +

 

"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +

 

"<TR BGCOLOR=\"#FFAD00\">\n" +

 

" <TH>Info Type<TH>Value\n" + "<TR>\n" +

 

"  <TD>ID\n" +

 

" <TD>" + session.getId() + "\n" + "<TR>\n" +

 

"  <TD>Creation Time\n" +

 

"  <TD>" +

 

new Date(session.getCreationTime()) + "\n" + "<TR>\n" +

 

"  <TD>Time of Last Access\n" +

 

"  <TD>" +

 

new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" +

 

"  <TD>Number of Previous Accesses\n" +

 

" <TD>" + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>"); }

 

/** Handle GET and POST requests identically. */ public void doPost(HttpServletRequest request, HttpServletResponse response)

 

throws ServletException, IOException { doGet(request, response);

 

}}

 

 

The Servlet Cookie API

 

To send cookies to the client, a servlet should create one or more cookies with designated names and values with new Cookie(name, value), set any optional attributes with cookie.setXxx

 

(readable later by cookie.getXxx), and insert the cookies into the response headers with response.addCookie(cookie). To read incoming cookies, a servlet should call request.getCookies, which returns an array of Cookie objects corresponding to the cookies the browser has associated with your site (this is null if there are no cookies in the request). In most cases, the servlet loops down this array until it finds the one whose name (getName) matches the name it had in mind, then calls getValue on that Cookie to see the value associated with that name. Each of these topics is discussed in more detail in the following sections.

 

 

Creating Cookies

 

You create a cookie by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain white space or any of the following characters: [ ] ( ) = , " / ? @ : ;

 

Cookie Attributes

 

 

Before adding the cookie to the outgoing headers, you can set various characteristics of the cookie by using one of the following setXxx methods, where Xxx is the name of the attribute you want to specify. Each setXxx method has a corresponding getXxx method to retrieve the attribute value. Except for name and value, the cookie attributes apply only to outgoing cookies from the server to the client; they aren’t set on cookies that come from the browser to the server. See Appendix A (Servlet and JSP Quick Reference) for a summarized version of this information.

 

public String getComment()

 

public void setComment(String comment)

 

 

These methods look up or specify a comment associated with the cookie. With version 0 cookies (see the upcoming subsection on getVersion and setVersion), the comment is used purely for informational purposes on the server; it is not sent to the client.

 

 

public String getDomain()

 

public void setDomain(String domainPattern)

 

These methods get or set the domain to which the cookie applies. Normally, the browser only returns cookies to the exact same hostname that sent them. You can use setDomain method to instruct the browser to return them to other hosts within the same domain. To prevent servers setting cookies that apply to hosts outside their domain, the domain specified is required to start with a dot (e.g.,.prenhall.com), and must contain two dots for noncountry domains like .com,

 

.edu and .gov; and three dots for country domains like .co.uk and .edu.es. For instance, cookies sent from a servlet at bali.vacations.com would not normally get sent by the browser to pages at mexico.vacations.com. If the site wanted this to happen, the servlets could specify cookie.setDomain(".vacations.com").

 

public int getMaxAge()

 

public void setMaxAge(int lifetime)

 

These methods tell how much time (in seconds) should elapse before the cookie expires. A negative value, which is the default, indicates that the cookie will last only for the current session (i.e., until the user quits the browser) and will not be stored on disk. See the LongLivedCookie class (Listing 8.4), which defines a subclass of Cookie with a maximum age automatically set one year in the future. Specifying a value of 0instructs the browser to delete the cookie.

 

public String getName()

 

public void setName(String cookieName)

 

This pair of methods gets or sets the name of the cookie. The name and the value are the two pieces you virtually always care about. However, since the name is supplied to the Cookie constructor, you rarely need to call setName. On the other hand, getName is used on almost every cookie received on the server. Since the getCookies method of HttpServletRequest returns an array of Cookie objects, it is common to loop down this array, calling getName until you have a particular name, then check the value with getValue.

 

public String getPath()

 

public void setPath(String path)

 

These methods get or set the path to which the cookie applies. If you don’t specify a path, the browser returns the cookie only to URLs in or below the directory containing the page that sent the cookie. The setPath method can be used to specify something more general. For example, someCookie.setPath("/") specifies that all pages on the server should receive the cookie. The path specified must include the current page; that is, you may specify a more general path than the default, but not a more specific one.

 

public boolean getSecure()

 

public void setSecure(boolean secureFlag)

 

This pair of methods gets or sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e., SSL) connections. The default is false; the cookie should apply to all connections.

 

public String getValue()

 

public void setValue(String cookieValue)

 

The getValue method looks up the value associated with the cookie; the setValue method specifies it. Again, the name and the value are the two parts of a cookie that you almost always care about, although in a few cases, a name is used as a boolean flag and its value is ignored (i.e., the existence of a cookie with the designated name is all that matters).

 

public int getVersion()

 

public void setVersion(int version)

 

 

These methods get/set the cookie protocol version the cookie complies with. Version 0, the default,

 

Placing Cookies in the Response Headers

 

 

The cookie is inserted into a Set-Cookie HTTP response header by means of the addCookie method of HttpServletResponse. The method is called addCookie, not setCookie, because any previously specified SetCookie headers are left alone and a new header is set. Here's an example:

 

 

Cookie userCookie = new Cookie("user", "uid1234"); userCookie.setMaxAge(60*60*24*365); // 1 year response.addCookie(userCookie);

 

Reading Cookies from the Client

 

 

To send cookies to the client, you create a Cookie, then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, you call getCookies on the HttpServletRequest. This call returns an array of Cookie objects corresponding to the values that came in on the Cookie HTTP request header. If there are no cookies in the request, getCookies returns null. Once you have this array, you typically loop down it, calling getName on each Cookie until you find one matching the name you have in mind. You then call getValue on the matching Cookie and finish with some processing specific to the resultant value. This is such a common process that Section 8.5 presents two utilities that simplify retrieving a cookie or cookie value that matches a designated cookie name.

 

 

Examples of Setting and Reading Cookies

 

 

The following program shows the SetCookies servlet, a servlet that sets six cookies. Three have the default expiration date, meaning that they should apply only until the user next restarts the browser. The other three use setMaxAge to stipulate that they should apply for the next hour, regardless of whether the user restarts the browser or reboots the computer to initiate a new browsing session.

 

 

SetCookies.java

 

 

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

import javax.servlet.http.*;

 

 

/** Sets six cookies: three that apply only to the current

 

*  session (regardless of how long that session lasts)

 

*  and three that persist for an hour (regardless of

 

*  whether the browser is restarted).

 

*/

 

public class SetCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)

 

throws ServletException, IOException { for(int i=0; i<3; i++) {

 

// Default maxAge is -1, indicating cookie

 

 

// applies only to current browsing session.

 

Cookie cookie = new Cookie("Session-Cookie " + i, "Cookie-Value-S" + i); response.addCookie(cookie);

 

cookie = new Cookie("Persistent-Cookie " + i, "Cookie-Value-P" + i);

 

//  Cookie is valid for an hour, regardless of whether

 

//  user quits browser, reboots computer, or whatever.

 

cookie.setMaxAge(3600);

 

response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies"; out.println (ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" +

 

"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "There are six cookies associated with this page.\n" + "To see them, visit the\n" +

 

"<A HREF=\"/servlet/coreservlets.ShowCookies\">\n" + "<CODE>ShowCookies</CODE> servlet</A>.\n" + "<P>\n" +

 

"Three of the cookies are associated only with the\n" + "current session, while three are persistent.\n" +

 

"Quit the browser, restart, and return to the\n" + "<CODE>ShowCookies</CODE> servlet to verify that\n" + "the three long-lived ones persist across sessions.\n" + "</BODY></HTML>");

 

}   }

 

The following program demonstrates a servlet that creates a table of all the cookies sent to it in the request.

 

 

ShowCookies.java

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

 

 

/** Creates a table of the cookies associated with the current page. */ public class ShowCookies extends HttpServlet {

 

public void doGet(HttpServletRequest request, HttpServletResponse response)

 

throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Active Cookies";

 

out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" +

 

"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" +

 

"  <TH>Cookie Name\n" +

 

"  <TH>Cookie Value");

 

Cookie[] cookies = request.getCookies();

 

Cookie cookie;

 

for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println("<TR>\n" +

 

"   <TD>" + cookie.getName() + "\n" +

 

"   <TD>" + cookie.getValue());

 

} out.println("</TABLE></BODY></HTML>");   } }

 

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : Applets : Java - The Session Tracking API |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.