In the last guide, I have covered Sessions in Servlet. Here we will discuss Cookies which is also used for session management. Let’s recall few things here from last tutorial so that we can relate sessions and cookies. When a user visits web application first time, the servlet container crates new HttpSession object by calling request.getSession(). A unique Id is assigned to the session. The Servlet container also sets a Cookie in the header of the HTTP response with cookie name and the unique session ID as its value.
The cookie is stored in the user browser, the client (user’s browser) sends this cookie back to the server for all the subsequent requests until the cookie is valid. The Servlet container checks the request header for cookies and get the session information from the cookie and use the associated session from the server memory.
The session remains active for the time specified in tag in web.xml. If tag in not set in web.xml then the session remains active for 30 minutes. Cookie remains active as long as the user’s browser is running, as soon as the browser is closed, the cookie and associated session info is destroyed. So when the user opens the browser again and sends request to web server, the new session is being created.
Types of Cookies
We can classify the cookie based on their expiry time:
- Session
- Persistent
1) SessionCookies:
Session cookies do not have expiration time. It lives in the browser memory. As soon as the web browser is closed this cookie gets destroyed.
2) Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the user hard drive and gets destroyed based on the expiry time.
How to send Cookies to the Client
Here are steps for sending cookie to the client:
- Create a Cookie object.
- Set the maximum Age.
- Place the Cookie in HTTP response header.
1) Create a Cookie object:
Cookie c = new Cookie("userName","Chaitanya");
2) Set the maximum Age:
By using setMaxAge () method we can set the maximum age for the particular cookie in seconds.
c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie()
method.
response.addCookie(c);
How to read cookies
Cookie c[]=request.getCookies(); //c.length gives the cookie count for(int i=0;i<c.length;i++){ out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue()); }
Example of Cookies in java servlet
index.html
<form action="login"> User Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPassword"/><br/> <input type="submit" value="submit"/> </form>
MyServlet1.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = request.getParameter("userPassword"); pwriter.print("Hello "+name); pwriter.print("Your Password is: "+password); //Creating two cookies Cookie c1=new Cookie("userName",name); Cookie c2=new Cookie("userPassword",password); //Adding the cookies to response header response.addCookie(c1); response.addCookie(c2); pwriter.print("<br><a href='welcome'>View Details</a>"); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } } }
MyServlet2.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); //Reading cookies Cookie c[]=request.getCookies(); //Displaying User name value from cookie pwriter.print("Name: "+c[1].getValue()); //Displaying user password value from cookie pwriter.print("Password: "+c[2].getValue()); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } } }
web.xml
<web-app> <display-name>BeginnersBookDemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>
Output:
Welcome Screen:
After clicking Submit:
After clicking View Details:
Methods of Cookie class
public void setComment(String purpose): This method is used for setting up comments in the cookie. This is basically used for describing the purpose of the cookie.
public String getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
public void setMaxAge(int expiry): Sets the maximum age of the cookie in seconds.
public int getMaxAge(): Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until browser shutdown.
public String getName(): Returns the name of the cookie. The name cannot be changed after creation.
public void setValue(String newValue): Assigns a new value to this Cookie.
public String getValue(): Gets the current value of this Cookie.
The list above has only commonly used methods. To get the complete list of methods of Cookie class refer official documentation.
Ashrumochan says
We can call the Session Cookies as “IN-Memory Cookies” as it lives in the memory.