Share on Google+Share on Google+

Read Cookies from Servlet

This section illustrates you how to read cookies from Servlets.

Read Cookies from Servlet


This section illustrates you how to read cookies from Servlets.

The Cookie Class provides an easy way to read Cookies. You can use getCookies() method to retrieve all the cookies in your servlet program.

This getCookies() method returns an array of cookie objects. In this example we will show you how you can retrieve all the cookies and display using servlets. 

Here is the code of

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException, {
  Cookie cookie = null;
  Cookie[] cookies = request.getCookies();
  boolean newCookie = false;

  if (cookies != null) {
  for (int i = 0; i < cookies.length; i++) {
  if (cookies[i].getName().equals("Cookies")) {
  cookie = cookies[i];
  if (cookie == null) {
  newCookie = true;
  int maxAge;
  try {
  maxAge = new Integer(getServletContext()
  catch (Exception e) {
  maxAge = -1;
  cookie = new Cookie("Cookies", "" + getNextCookieValue());
  response.setContentType("text/html"); out = response.getWriter();
  out.println("<title>Read Cookie</title>");
  ("<h2> Our Cookie named \"Cookies\"information</h2>");
   out.println("Cookie value: " + cookie.getValue() + "<br>");
  if (newCookie) {
  ("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
  out.println("Cookie Path: " + cookie.getPath() + "<br>");
  private long getNextCookieValue() {
 return new java.util.Date().getTime();
  public void doPost(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, {
  doGet(request, response);

web.xml for


After Calling the request, cookie value, cookie maxAge, cookie path along with cookie name, will be displayed on the browser. And after reloading Cookie value has been changed with getNextCookieValue() method.

Output will be displayed as:

After reloading the application cookie value will be changed, output will be:

Download Source Code


Posted on: July 19, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Read Cookies from Servlet   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image