Java Servlet Cookies Example

Filed Under: Java EE

Welcome to Java Servlet Cookies example. Cookies are used a lot in web client-server communication, it’s not something specific to java.

Some of the common usage of cookies are:

  1. Session authentication using Cookies, we learned in Servlet Session Tutorial that HttpSession uses “JSESSIONID” cookie to keep track of the user session.
  2. Personalized response to the client based on their preference, for example we can set background color as cookie in client browser and then use it to customize response background color, image etc.

Cookies in Java Servlet

cookies in java, cookies in servlet, java cookie example
Cookies are text data sent by server to the client and it gets saved at the client local machine. When client send request to server, it passes the cookies stored by the server in request header like below:


Cookie	Test="Test Cookie5"

Client can send multiple cookies to server and we can disable cookies to get stored at client side from browser preferences. Apart from the key-value pairs, server sends some other data to client in response header and it looks something like below.


Set-Cookie	Counter=7;
Version=1;
Comment="SetCookie Counter";
Domain="localhost";
Max-Age=86400;
Expires=Thu, 15-Aug-2013 20:19:19 GMT;
Path=/cookie/SetCookie

Set-Cookie	Test="Test Cookie7";
Version=1;
Comment="Test Cookie"

Note that server sends some additional information for cookie, such as comment, domain, maximum time before cookie expires and Path where browser should send the cookie back in request. But when client sends cookie to browser, it only sends the name and value of the cookie.

Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.

HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.

Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

Cookie class has a single constructor that takes name and value because they are mandatory parameters for a cookie, all other parameters are optional.

Some important methods of Cookie class are:

  1. getComment() – Returns the comment describing the purpose of this cookie, used at client side. Note that server doesn’t receive this information when client sends cookie in request header. We can use setComment() method to set cookie description at server side.
  2. getDomain() – returns the domain name for the cookie. We can use setDomain() method to set the domain name for cookie, if domain name is set then the cookie will be sent only to that particular domain requests.
  3. getMaxAge() – returns the maximum age in seconds. We can use setMaxAge() to set the expiration time of cookie.
  4. getName() – returns the name of the cookie, can be used at both browser and server side. There is no setter for name, we can set name once through constructor only.
  5. getPath() – Returns the path on the server to which the browser returns this cookie. We will see it’s example where the cookie will be sent to specific resource only. We can use setPath() to instruct browser to send cookie to a particular resource only.
  6. getSecure() – Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. We can use setSecure() method to instruct browser to send cookie only over secured protocol.
  7. getValue() – returns the value of the cookie as String. There is also setValue() method to change the value of cookie.
  8. getVersion() – Returns the version of the protocol this cookie complies with. There is also a setter method for version.
  9. isHttpOnly() – Checks whether this Cookie has been marked as HttpOnly. There is also a setter method that we can use to instruct client to use it for HTTP only.

Java Servlet Cookie Example

We will create two simple servlets to print cookies from client, in one of the servlet we will set a cookie for every domain and a cookie with Path settings so that other servlet won’t receive this from client.

Our final project structure for cookies in java servlet will look like below image.

Cookies in Java, Cookies in Servlet, java cookie example

SetCookie.java: This servlet will set some cookies and send it to browser. It will also print cookie information and send it as HTML response.


package com.journaldev.servlet.cookie;

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("/cookie/SetCookie")
public class SetCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static int count = 0;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		Cookie[] requestCookies = request.getCookies();
		
		out.write("<html><head></head><body>");
		out.write("<h3>Hello Browser!!</h3>");
		if(requestCookies != null){
		out.write("<h3>Request Cookies:</h3>");
		for(Cookie c : requestCookies){
			out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment()
					+", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath()
					+", Version="+c.getVersion());
			out.write("<br>");
		}
		}
		//Set cookies for counter, accessible to only this servlet
		count++;
		Cookie counterCookie = new Cookie("Counter", String.valueOf(count));
		//add some description to be viewed in browser cookie viewer
		counterCookie.setComment("SetCookie Counter");
		//setting max age to be 1 day
		counterCookie.setMaxAge(24*60*60);
		//set path to make it accessible to only this servlet
		counterCookie.setPath("/ServletCookie/cookie/SetCookie");

		//adding cookie to the response
		response.addCookie(counterCookie);
		
		//set a domain specific cookie
		Cookie domainCookie = new Cookie("Test", "Test Cookie"+String.valueOf(count));
		domainCookie.setComment("Test Cookie");
		response.addCookie(domainCookie);
		
		out.write("</body></html>");
	}

}

GetCookie.java: A simple servlet that will demonstrate that the cookie set in SetCookie with specific Path will not be send by browser to this servlet.


package com.journaldev.servlet.cookie;

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("/cookie/GetCookie")
public class GetCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		Cookie[] requestCookies = request.getCookies();
		
		out.write("<html><head></head><body>");
		out.write("<h3>Hello Browser!!</h3>");
		if(requestCookies != null){
		out.write("<h3>Request Cookies:</h3>");
		for(Cookie c : requestCookies){
			out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment()
					+", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath()
					+", Version="+c.getVersion());
			out.write("<br>");
			//delete cookie
			if(c.getName().equals("Test")){
				c.setMaxAge(0);
				response.addCookie(c);
			}
		}
		}
		out.write("</body></html>");
	}

}

When you will run the program, you will notice few things:

  • Cookie “Counter” is sent over to the SetCookie only, GetCookie will never receive this cookie.
  • Except name and value all other variables are printing default values. MaxAge default value is -1 and version default value is 0.
  • GetCookie is setting max age of “Test” cookie to 0, so that it will be expired and deleted by client browser.

That’s all for cookies in java and it’s usage in Servlet API, you might want to check out other servlet tutorials too.

  1. Java Web Application
  2. Servlet JSP Tutorial
  3. Session Management in Java
  4. Java Servlet Filter
  5. Servlet Listener

Check out next articles in series about Servlet Exception Handling and Servlet File Upload Download Example.

Comments

  1. mouli says:

    i had developed a simple web app ….setting cookie works perfectly in my pc but, when my app is acesed using my ip address on other pc ,.cookie was not there ……what is the problem?

  2. Prabhakara Gangi says:

    Hi Pankaj,

    If we won’t set domain name in the Cookie then who/which code would be assigning the domain name?

    Thanks,
    Gangi

  3. aa says:

    Download is not possible…pls enable it.

    1. Pankaj says:

      I just tried and able to download the project. Check if any browser popup blocker is blocking it from being downloaded?

  4. sumit says:

    hey can we read cookies written by any other server or servlet

  5. vyshag says:

    can anyone tell me if i can run this code on netbeans??if yes please tell how…

  6. Nurul says:

    currently i have a problem in creating nag counter using servlet, the hard one is how do we create a cookie without the user entered any name or other fields. it is a pleasure if you can put some words on it.

  7. Javix says:

    I think there is a typo in referencing the servlet classes, – you call them as SetServlet and GetServlet in your comments but the real name of classes (servlets) are SetCookie and GetCookie respectively.

  8. Arun says:

    Nice set of articles.

  9. Akash says:

    Hi, i want a simple example for, write a java program to implement session and cookies with a programming example?

  10. Java Pathshala says:

    Nice Article. Make sense.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages