Online-Academy

Look, Read, Understand, Apply

Menu

Cookie

Cookie

HTTP protocol used in the communication between client and server in the Internet is stateless protocol. HTTP protocol is called stateless because the state between client and server during the communication is not maintained; server doesn't known if the client has requested it for any service/information before or not; each request is executed independently of the past requests, if the client has made any, by the server .

Cookie is a small piece of information stored by the webserver on the web browser of the client. Using Cookie server can know about the client; if the client has requested for service or information before or not. Cookie has name and value; age of Cookie can also be specified.

Creating cookie

In Java Servlet, Cookie is created using inbuilt Cookie class.

Cookie cook = new Cookie("cname","Value_of_Cookie");

Here Cookie is created using Cookie constructor; two parameters are provided to the Cookie constructor: name of the cookie and value of the cookie, (value of the cookie can't contain space).

The created Cookie is then added to Cookie list using HttpServletResponse object (defined as parameter to doGet() or doPost() method).

response.addCookie(cook);

Different pages can set different cookies. Cookie is stored in the array of Cookie.

To use Cookie in Servlet, javax.servlet.http.Cookie must be imported.

Reading Cookie

To read cook, object of HttpServletRequest is used. Method getCookies() of the HttpServletRequest object retrieves all the cookies stored in the web browser. The returned cookies are stored in the array of Cookie.

Cookie[] cooks = request.getCookies();

Information about the cookies can be retrieved using getName() and getValue() methods of Cookie class

PrintWriter pw = response.getWriter();
for(int i=0;i<cooks.length;i++)
{
	pw.write("Cookie: "+cooks[i].getName()+":"+cooks.getValue());
}

The following programs show show to set cookie and read cookie. Two cookies are set by two different servlets: MySearcher and anotherCookie.

A html page is created to send a value to MySearcher servlet; in MySearcher servlet cookie is created and set using the value provided from the html page.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Search Page</title>
</head>
<body>
<form action="MySearcher">  
<input type="text" name="name">  
<input type="submit" value="Google Search">  
</form>  
</body>
</html>
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
public class MySearcher extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public MySearcher() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
		String name=request.getParameter("name");   
		Cookie cook = new Cookie("user",name);
		response.addCookie(cook);
		PrintWriter pw = response.getWriter();
		pw.write("<a href='cookie_config'>Cookie and Config</a>");
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

In servlet anotherCookie, cookie is created. Name of cookie is username and value of the cookie is "TomCruise";

import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class anotherCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public anotherCookie() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
		PrintWriter pw = response.getWriter();
		pw.write("<h5>Dinesh JEE</h5>");
		Cookie cc = new Cookie("username","TomCruise");
		response.addCookie(cc);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Third servlet "cookie_config" is created to read the cookie set by MySearcher and anotherCookie servlets.

PrintWriter pw = response.getWriter();
Cookie ck[]=request.getCookies();  
		for(int i=0;i<ck.length;i++){  
			pw.write("Cookie: "+i+":"+ck[i].getValue());
		}

In this servlet parameter provided in the web.xml (deployment descriptor) is also read.

ServletContext ct = getServletContext();
String email= getServletConfig().getInitParameter("email");
import javax.servlet.ServletContext;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
public class cookie_config extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public cookie_config() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
		PrintWriter pw = response.getWriter();
		pw.write("Number : ");
		String email= getServletConfig().getInitParameter("email");
		pw.write("Value: "+email);
		
		ServletContext ct = getServletContext();
		String owner = ct.getInitParameter("Owner");
		pw.write("<br>Owner is: "+owner);
		Cookie ck[]=request.getCookies();  
		for(int i=0;i<ck.length;i++){  
			pw.write("Cookie: "+i+":"+ck[i].getValue());
		}
			pw.close();
		}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>july_2021</display-name>
  <servlet>
  	<servlet-name>MySearcher</servlet-name>
  	<servlet-class>MySearcher</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>MySearcher</servlet-name>
  	<url-pattern>/MySearcher</url-pattern>
  </servlet-mapping>
  <servlet>
  	<servlet-name>anotherCookie</servlet-name>
  	<servlet-class>anotherCookie</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>anotherCookie</servlet-name>
  	<url-pattern>/anotherCookie</url-pattern>
  </servlet-mapping>
  <servlet>
  	<servlet-name>prime_number</servlet-name>
  	<servlet-class>prime_number</servlet-class>
  	<init-param>
    	<param-name>email</param-name>
    	<param-value>dinesh8np@gmail.com</param-value>
	</init-param>
  </servlet>
  <context-param>
  	<param-name>Owner</param-name>  
	<param-value>Dinesh Jee</param-value>  
  </context-param>
  <servlet-mapping>
  	<servlet-name>prime_number</servlet-name>
  	<url-pattern>/prime_number</url-pattern>
  </servlet-mapping>
</web-app>