Servlet cookies tutorial with example

This servlet cookies tutorial shows you how to create, retrive and delete a cookie from browser using servlet application

Cookie is a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie’s value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

How to create cookies in java

Cookie ck=new Cookie("auth","candidjava");

Servlet cookie max age

You can set expire time for the cookie using setmaxAge method, this method accepts seconds

ck.setMaxAge(600); // 600 sec ie.. 10 min

Servlet set cookie to browser

You can use response object to add cookie to the browser, you can also create more number of cookie and add it to a single response object


Servlet request get cookie

Cookie are retrived from browser as an array, you can use request object getCookies method to access all cookie created by your domain.

Cookie[] cks=request.getCookies()

Delete Servlet cookie

To delete a cookie just recreate the cookie in the same name and set value as null and age as null.

Cookie ck=new Cookie("auth",null);

A negative value in the above method means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

Browser cookie limits and limit per domain

The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

Servlet Cookie Example


<!DOCTYPE html>
<meta charset="UTF-8">
<title>Insert title here</title>

<h1>Simple Cookie example</h1>

<form action="CookieController" method="post">
        Username: <input type="text" name="uname"> <br>
   Password: <input type="password" name="pass"> <br>
<input type="submit" value="Login">

Servlet CookieController to create cookie

package com.candidjava;

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 CookieController
public class CookieController extends HttpServlet {

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
      String un = request.getParameter("uname");
      String pw = request.getParameter("pass");

      Cookie ck = new Cookie("mycookie", un);




Display list of Cookie in browser

<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<h1>Retrieving Cookie from browser</h1>
   Cookie[] cks=request.getCookies();
   for(Cookie ck:cks)
      String cn=ck.getName();
      String cv=ck.getValue();
      Cookie name : <b><%=cn %> </b><br>
      Cookie Value : <b><%=cv %> </b><br>

Output Screenshot:

Screenshot 1

Screenshot 2

Download source code

Cookie example war

Cookie example zip

Let’s learn some more methods in  servlet cookies tutorial

Servlet get cookie path

We can get the path of the cookie by below method.
getPath():- Returns the path on the server to which the browser returns this cookie.

Servlet set cookie path

Path of the cookie can be set by below method.
setPath(java.lang.String uri):-Specifies a path for the cookie to which the client should return the cookie.

Set cookie domain

Cookie domain can be set by below method.
setDomain(java.lang.String domain):- Specifies the domain within which this cookie should be presented.

Servlet cookie httpOnly

setHttpOnly(boolean isHttpOnly):-Marks or unmarks this Cookie as HttpOnly.

Servlet set cookie expiry date

We can set the expiry date of the cookie by below method.
setMaxAge(int expiry):- Sets the maximum age in seconds for this Cookie.


Leave a Reply

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