29 Servlets – Session and Cookies
Dr M. Vijayalakshmi
Persistent Information
A server site typically needs to maintain two kinds of persistent information.
Information about the session
A session starts when the user logs in and continues until the user logs out or completes the transaction. (For e.g., making a purchase online)
Information about the user
User information must generally be maintained much longer than session information (For e.g., remembering a purchase i.e., login ID and a password.). This information must be stored on the server, for example on a file or in a database.
Need for Session Tracking
HTTP is a “stateless” protocol. Each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Moreover, the server cannot identify from which client it is getting requests. Hence there arises a need that the server must be able to keep track of multiple conversations with multiple users.
What is a Session?
A Session is a unique identification number maintained between the web client and the web server. There are four ways to maintain session between a web client and a web server. They are,
1. Hidden Form Fields – standard model for XML documents.
2. Cookies – standard model for any structured document.
3. URL Rewriting – standard model for HTML documents.
4. Java’s Session Tracking API can be used to do most of the work.
Let us now discuss about each of the above approaches in maintaining session during client server interaction.
Hidden <form> fields
A Hidden Form Field is a hidden textfield in HTML which is used to maintain the state of an user. Here we can store the information in a hidden field and receive it from another Servlet.
The code to store value in hidden field is given below,
<input type=”hidden” name=”sessionID” value=”…”>
The advantages of this approach is that this field needs to know how to read servlet parameters, thereby efficient as it minimizes repeated calls to the server.
The disadvantages of this approach are, the information is lost when browser quits or goes to another page. It is also useless for maintaining persistent information about a user. Moreover, there are chances to be spoofed since the session ID must be incorporated into every HTML page and every HTML page must be dynamically generated.
However, Hidden fields are good for session tracking (i.e., holding a “conversation” with the user). It is also simple and efficient.
It is also possible that a web server can send a hidden HTML form field along with a unique Session Id.
<input type=“hidden” name=“sessionid” value=“12345”>
When the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, session_id value can be used to keep the track of different web browsers.
Cookies
A cookie is a small bit of text sent to the client that can be read again later. The web server can assign a unique Session ID as a Cookie. To each web client and for subsequent requests from the client can be recognized using the received cookie. But, this not an effective way because many time browser does not support a cookie. Moreover, it is not recommended to use this procedure to maintain the sessions.The expiration date of a cookie determines how long the cookie remains on the client’s computer.
Creating Cookies
We can use the constructor of the class Cookie to create a Cookie in Java. The syntax of creating cookies is given below,
Cookie Class
Constructor
Cookie (String name, String value)
The constructor of the Cookie class takes two parameters, the name of the cookie and the value stored as cookie.
Methods
Some of the methods generally used with Cookies in the Cookie class are listed as below.Detailed explanation of these are available in the next section.
public void setMaxAge(int expiry)
public void setValue(String newValue)
The Cookies created can be added to the HttpServletResponse by using the method,
void addCookie(Cookie cookie)
The Cookie values can be obtained from the HttpServletRequest by using the method,
Cookie[] getCookies()
Using Cookies
To work with Cookies, first import the package
import javax.servlet.http.*;
To create the Cookie, use the constructor of the Cookie class.
Constructor:
Cookie(String name, String value)
Assuming request is an HttpServletRequest and response is an HttpServletResponse, the snippet code is given,The Cookie is added to the HttpServletResponse and the Cookie values are retrieved from HttpServletRequest.
The retrieved Cookies are stored in a Cookie array called “cookies“. From each Cookie object, we can use the method getName() to retrieve the name of the Cookie and the method getValue() is used to retrieve the value of the Cookie.
response.addCookie(cookie);
Cookie[]cookies = request.getCookies();
String name = cookies[i].getName();
String value = cookies[i].getValue();
Cookie Methods
public void setComment(String purpose)
This method specifies a comment that describes a cookie’s purpose. The comment is useful if the browser presents the cookie to the user.
public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don’t set this, the cookie will last only for the current session.
public int getMaxAge()
This method returns the Max age in seconds after which cookie will expire. If expiry is negative, the Cookie is deleted when browser exits. If expiry is zero, the Cookie is deleted immediately.
public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
public boolean getSecure()
Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL .
Cookie Example
An example to illustrate cookies is given below.
First we create an HTML page to call the servlet “AddCookieServlet”. This HTML page displays a textbox where we can enter a text to be stored as a cookie value and a submit button to submit the request to the Web server.
Index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
</head>
<body>
<center>
<form method=”post” action=”AddCookieServlet”> <B>Enter a value for MyCookie: </B> <input type=”text” name=”data” size=”25″>
<input type=”submit” value=”Submit”>
</form>
</center>
</body>
</html>
Output of Index.html
Example: AddCookieServlet
The code to develop AddCookieServlet is given below,
In the AddCookieServlet, we retrieve the text value that is sent from the web client using the getParameter() method with the HttpServletRequest object. We then create a cookie using the constructor of the Cookie class for the retrieved value and we write the cookie to the HttpServletResponse object.
The response is written to the client as ” My Cookie has been set to” with the cookie value displayed to the client and a link is written to the client as ” To view your cookie, Click here”. When the user clicks the link, another servlet GetCookiesServlet is executed which displays the Cookie name and Cookie value.
Here in this example the cookie is identified by a name, “MyCookie”, and has a value that is entered in the text box . Thus, we can add many different cookies with different names.
//AddCookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AddCookieServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException { response.setContentType(“text/html;charset=UTF-8”); try (PrintWriter out = response.getWriter()) { String data=request.getParameter(“data”);
Cookie cookie=new Cookie(“MyCookie”,data);
response.addCookie(cookie);
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet AddCookieServlet</title>”);
out.println(“</head>”);
out.println(“<body><center>”);
out.println(“<B>My Cookie has been set to</B>”);
out.println(data);
out.println(“<br>
<a Href=’http://localhost:8088/UsingCookies/GetCookiesServlet’>To view your cookie, Click here </a>”);
out.println(“</center></body>”);
out.println(“</html>”); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
processRequest(request, response);
}
}
The output of the above code is shown in Figure 31.2.
Example: GetCookiesServlet
This servlet is executed when the user clicks the link shown in the output screen of AddCookieServlet. This GetCookiesServlet retrieves the cookie using the method getCookies() of the HttpServletRequest object. The method returns an array of cookies stored whose values can be accessed using the methods getName() and getValue(). The Cookie[] array is iterated to get the cookie name and the cookie value which is then written to the response and displayed in the client page.
//GetCookiesServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetCookiesServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
try {
PrintWriter out = response.getWriter()
Cookie[] cookie=request.getCookies();
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet GetCookiesServlet</title>”);
out.println(“</head>”);
out.println(“<body><center>”);
out.println(“<B>”);
for(int i=0; i<cookie.length; i++)
{
String name=cookie[i].getName(); String value = cookie[i].getValue(); out.println(“Name = “+ name +”; Value = “+value);
}
out.println(“</center></body>”);
out.println(“</html>”);
out.close();
}
}
Protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
Output – GetCookieServlet
The output of the above code is shown in Figure 31.3.
Web.xml
We need to compile the above servlets, AddCookieServlet and GetCookiesServlet and create appropriate entry in web.xml file.
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd” version=”3.1″>
<session-config>
<session-timeout>
</session-timeout>
</session-config>
<servlet>
<servlet-name>AddCookie</servlet-name> <servlet-class>AddCookieServlet</servlet-class> </servlet>
<servlet-mapping>
<servlet-name>AddCookie</servlet-name>
<url-pattern>/AddCookieServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>GetCookies</servlet-name>
<servlet-class>GetCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookies</servlet-name>
<url-pattern>/GetCookiesServlet</url-pattern>
</servlet-mapping>
</web-app>
URL Rewriting
Session Management can be done with URL Rewriting when the client has disabled cookies in the browser. URL rewriting will always work browser independent.
In URL rewriting, a token(parameter) can be added at the end of the URL. The token consist of name/value pair separated by an equal(=) sign. Using this token, we can append some extra data at the end of each URL that identifies the session. The server can then associate that session identifier with data it has stored about that session.
We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.
Drawbacks:
It will generate every URL dynamically to assign a session ID where page is simple static HTML page.If the user has cookies turned off, we can use URL rewriting. URL rewriting is only used as a backup for cookies.It adds the session ID to the end of every URL:
URL + ;jsessionid=0ABCDEF98765
This is almost automatic, but Cookies must fail, and must explicitly “encode” (add the extra information to) URLs,
For example:
out.println(“<a href=\”” + response.encodeURL(yourURL) + “\”>click me</a>”);
Java’s Session Tracking API
Session Management in Java Servlet Web Applications is a very interesting topic. Session in Java Servlet are managed through different ways, such as Cookies, HttpSession API, URL rewriting etc.In the next module we will learn about session management with servlets using HttpSession API.
Benefits of Session Management
• Personalization
This makes it possible for e-businesses to communicate effectively with their customers. It improves the user’s ability to locate desired products and services.
• Privacy
Trade-off exists, between personalized e-business service and protection of privacy.
- Recognizing Clients
To provide personalized services to consumers, e-businesses must be able to recognize clients when they request information from a site.
Summary
This module has explained about the need for Session Management and discussed about the different approaches of Session Management. It also gave an insight about how to maintain a session between a web client and a web server. This section provides us an understanding about the different methods to maintain sessions such as using cookies, hidden form fields and URL Rewriting. The next module we will explain about session management with servlets using HttpSession API.
References
- http://www.tutorialspoint.com/servlets/servlets-cookies-handling.htm
- www.cis.upenn.edu/~matuszek/cit597-2006/…/26-servlet-sessions.p