Servlets - create, store and read cookies

Cookies are bits of information which is send by a server to the browser. Later this saved information is returned unchanged from browser for various tasks. Some important uses of cookies are:

  • Identify a user.
  • Remember username and password.
  • Save user preferences.
  • Cookies helps to access a site faster

Creating a cookie

Cookies are created with the help of the cookie() constructor inside the servlet. Cookie constructor takes two arguments. First argument is the name of the cookie and second argument is the value of it.

Cookie passwordCookie = new Cookie("password", "abcde");

With the above code snippet a new cookie will be created by the name "password" which contains "abcde" as a information.

Session based Cookie

When you create a new cookie then by default it is a session cookie. It means that the life of a cookie is only till the user is accessing the browser. When user closes the web browser the cookie gets deleted.

How to extend life of a cookie

To extend the life of a cookie you need to set its maximum age using setMaxAge() function.


The above code sets the age of the cookie to be of one day.

How to send the cookie to a browser

By inserting a cookie into a response header we send the cookie to the client browser. We use addCookie() method of HttpServletResponse.

Cookies passwordCookie = new Cookie("password", "abcde");

In the next tutorial we are going to learn about getting data from cookies.

Reading a cookie from a browser

To receive cookies back from the client browser we use HttpServletRequest. We get an array which contains all cookies sent by the browser.

With the help of the steps illustrated below you can access the cookie object:

  • Use getCookies() to receive an array of cookie with the help of response object.
    Cookie[] cookies = request.getCookies();
  • Check if no cookie is returned by the browser.
    if(cookies != null){
  • Loop through the array to find the required cookie.
    for(i = 0; i<cookies.length; i++){
     Cookies cookie = cookies[i];
  • Get name of the cookie
    String name = cookie.getName();
  • Get Value of the cookie
    String value = cookie.getvalue();
  • Get life time of the cookie
    int time_left = cookie.getMaxAge();

Note: Generally the value of cookie is not readable by third party. To add more security you can add encryption to your information.