Friday, November 15, 2013

Servlet Cookie Example Tutorial

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.

Cookie

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.

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.
The project structure will look like below image.
Servlet-Cookie-Project
SetServlet.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("");
  out.write("

Hello Browser!!

"); if(requestCookies != null){ out.write("

Request Cookies:

"); 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(" "); } } //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(""); } }
GetCookie.java: A simple servlet that will demonstrate that the cookie set in SetServlet 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("");
  out.write("

Hello Browser!!

"); if(requestCookies != null){ out.write("

Request Cookies:

"); 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(" "); //delete cookie if(c.getName().equals("Test")){ c.setMaxAge(0); response.addCookie(c); } } } out.write(""); } }
When you will run the program, you will notice few things:
  • Cookie “Counter” is sent over to the SetServlet only, GetServlet 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.
  • GetServlet 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 and it’s usage in Servlet API, you might want to check out other servlet tutorials too.
  1. Java Web Application
  2. Java Servlets
  3. Servlet Session Management
  4. Servlet Filter
  5. Servlet Listener
Updates

No comments: