Cookies Handling in Servlet

As of now, we have discussed Exception in Servlet and how to Handle it in Servlet. In this article, we will discuss Cookies and the Handling of cookies in Servlet.

Today, many websites use string text called cookies to store persistent client-side state between connection. Cookies are helpful for storing session ID, shopping cart contents, login credentials, etc.

What are Cookies?

Cookies are data packets that the computer receives, then sends back without altering it.

  • Whenever you visit any website, the website sends the cookie to your computer, your computer stores in the file located inside your web browser.

  • It is helpful in keeping track of your website visitors.
  • As we see now, we have different passwords and we cannot handle so many passwords so, whenever we log in, the browser asks us to save the password and then we click on save.

The Set-Cookie HTTP response header sends a cookie from the server to the client. A cookie looks like this

Set-Cookie <cookie-name>=<cookie-value>

This shows the server sending header to tell clients to store a pair of cookies.

HTTP/2.0 404 NOT FOUND
Content-Type:text/html
Set-Cookie:cookie_1=abc
Set-Cookie:cookie_2=abc1234

[Page content]

Whenever client request to the server, the browser send back all previously-stored cookie to the server in the following way

GET/hello.page HTTP/2.0
Host:www.abc.org
Cookie:cookie_1=abc,cookie_2=abc1234

The Lifetime of cookie

  • Session Cookies: This is deleted when the current session ends.
  • Permanent Cookies: This is deleted as per the specified Expired  date attribute
Set-Cookie: id=1234; Expires=Fri, 10 Feb 2022 :15:00 GMT;

Methods of Servlet Cookies

  • public void setDomain(String pattern): This method sets the domain to which cookie applies. for eg https://codedec.com/
  • public String getDomain(): This method returns the domain to which the cookie applies.
  • public void setMaxAge(int expiry): This method sets the expiry of the cookie.
  • public int getMaxAge(): This method returns the age of the cookie specified in second.
  • public String getName(): This method returns the name of the cookie.
  • public void setValue(String value): This method sets the values associate with cookies.
  • public String getValue(): This method returns the value associated with the cookie.
  • public void setPath(String uri): This method sets the path to which cookies applied.
  • public String getPath(): This method returns the path to which cookies apply.
  • public void setSecure(boolean flag): This method sets the value indicating whether the cookie should only be sent over an encrypted network.
  • public void setComment(String purpose): This method sets the comment for the cookie.
  • public void getComment(): This method returns the comment of the cookie.

How to set Cookies in Servlet?

  • Create a cookie
Cookie cookie=new Cookie("key","value");
  • Set the maximum age
cookie.setMaxAge(60*60*24)
  • Send the cookie
response.addCookie(cookie);

How to handle Cookies in Servlet?

Example to Set cookies in servlet and Get the cookies in servlet

A servlet uses the getCookies() method of HTTPServletRequest to retrieve cookies as request. The addCookie() method of HTTPServletResponse sends a new cookie to the browser. we can set the age of the cookie by setMaxAge() method.

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form action="abc" method="get">
    Username <input type="text" name="uname"> <input type="submit"
      value="Click" id="button-1" />
  </form>
</body>
</html>

Servlet1.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;

/**
 * Servlet implementation class Servlet1
 */
@WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public Servlet1() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter printWriter = response.getWriter();
    String name = request.getParameter("uname");
    printWriter.println("Hey " + name);
    Cookie cookie = new Cookie("username", name);
    response.addCookie(cookie);
    printWriter.println("<html><body>");
    printWriter.println("<form action='pqr' method='get'>");
    printWriter.println("<input type='submit' value='Click'>");
    printWriter.println("</form>");
    printWriter.println("</body></html>");
  }
}

Servlet2.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;

@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public Servlet2() {
    super();
    // TODO Auto-generated constructor stub
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter printWriter = response.getWriter();
    Cookie cookie[] = request.getCookies();
    printWriter.println("Hey " + cookie[0].getValue());
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  id="WebApp_ID" version="3.0">
  <display-name>CookiesHandlingDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>abc</servlet-name>
    <servlet-class>Servlet1</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>abc</servlet-name>
    <url-pattern>/abc</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>pqr</servlet-name>
    <servlet-class>Servlet2</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>pqr</servlet-name>
    <url-pattern>/pqr</url-pattern>
  </servlet-mapping>

</web-app>

Output

Uses of Cookie

  • Cookies are able to keep track of the website.
  • It is on the client-side.
  • Use to store login information of the user.