×
☰ See All Chapters

Servlet Cookies - how cookies work

A cookie is a small piece of information which contains name and value both of type String.  Cookies are stored at client side. We can use cookies to store client specific data but it is not a good approach because browser might not support cookies or client may delete cookie. Also storing values in cookie is not secure.

Cookie working mechanism - how cookies work

Cookie object will be created in server and will be moved to the client machine with response object and stored at the client machine. When browser sends the request to application all the cookies related to the application will be attached to request and will go to the server. Always cookie shuttles between client and server.

servlet-cookie-0
 

Types of Cookies

Two types of cookies presents in Servlets:

1. Non-persistent/session cookie: Browser removes each time when user closes the browser.

2. Persistent cookie: Browser removes only if user logout or sign-out.

We can specify the expiry time of the cookie. This set time is in seconds and the cookie will stay alive for this period even after the browser shuts down. It will be saved to the hard disk.

Cookie cookie = new Cookie("FIRST_NAME", “Manu”);

cookie.setMaxAge(300);

Constructors of Cookie class

Constructor

Description

Cookie( )

Constructs the cookie with default property.

Cookie(String name, String value)

Constructs a cookie with specified name and value.

Important Methods of Cookie Class

Methods

Description

public String getName( )

Returns the name of the cookies.

public String getPath( )

Returns the path of the server to which the browser returns the cookie.

public String getValue( )

Returns the value of the cookie.

public int getMaxAge( )

Returns the maximum age limit to the cookie, specified in seconds.

public void setMaxAge(int expiry)

Sets the maximum age of the cookies in seconds.

public void setValue(String newValue)

Allocates a new value to a cookie after the cookie is created.

 

Create a Cookie Object

Cookie cookie = new Cookie("name","Manu Manjunatha");

response.addCookie(cookie);

 

Reading Cookies in server

The getCookies( ) method of HttpServletRequest object is used for getting the cookie.

Cookie[] cookies = request.getCookies();

for (Cookie cookie : cookies) {

        out.print(cookie);

}

Deleting the Cookies

We can remove the cookies from the browser by setting the cookie expiry time to 0 or -1. If set to -1 then those will be removed when browser is closed. If set to 0 will be removed immediately. Also once cookie is created we can set the age up to which it will be alive.

Cookie[] ck = request.getCookies();

ck[0].setMaxAge(0);

ck[1].setMaxAge(-1);

                       

Cookie newCookie = new Cookie("Hello", "Hello");

newCookie.setMaxAge(500);

 

Example of Servlet Cookies

Project directory structure

servlet-cookie-1
 

home.html

<!DOCTYPE html>

<html>

<body>

<form action="../servlet1" method="post">  

Enter Personal Details:<br/>

Name:<input type="text" name="name"/><br/>  

<input type="submit" value="go"/>  

</form>  

</body>

</html>

FirstServlet.java

package com.java4coding;

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class FirstServlet extends HttpServlet {

 

        public void doPost(HttpServletRequest request, HttpServletResponse response) {

                try {

                        response.setContentType("text/html");

                        PrintWriter out = response.getWriter();

                        String name = request.getParameter("name");

                        out.print("Welcome " + name );

                        Cookie ck1 = new Cookie("name", name);

                        response.addCookie(ck1);

                        out.print("<form action='servlet2' method='post'> ");

                        out.print("Enter Contact Details:<br/>");

                        out.print("Address:<input type='text' name='address'/><br/>");

                        out.print("<input type='submit' value='go'/> ");

                        out.print("</form>");

                        out.close();

 

                } catch (Exception e) {

                        System.out.println(e);

                }

        }

}

 

SecondServlet.java

package com.java4coding;

import java.io.*;

import javax.servlet.http.*;

 

public class SecondServlet extends HttpServlet {

 

        public void doPost(HttpServletRequest request, HttpServletResponse response) {

                try {

                        response.setContentType("text/html");

                        PrintWriter out = response.getWriter();

                        String address = request.getParameter("address");

                        Cookie ck1 = new Cookie("address", address);

                        response.addCookie(ck1);

                        out.print("<form action='servlet3' method='post'> ");

                        out.print("Enter Eduction Details:<br/>");

                        out.print("Education:<input type='text' name='education'/><br/>");

                        out.print("<input type='submit' value='go'/> ");

                        out.print("</form>");

                        out.close();

 

                } catch (Exception e) {

                        System.out.println(e);

                }

        }

}

 

ThirdServlet.java

package com.java4coding;

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class ThirdServlet extends HttpServlet {

 

        public void doPost(HttpServletRequest request, HttpServletResponse response) {

                try {

 

                        response.setContentType("text/html");

                        PrintWriter out = response.getWriter();

                        Cookie ck[] = request.getCookies();

                        out.print("Name: " + ck[0].getValue()+ "</br>");

                        out.print("Address: " + ck[1].getValue()+ "</br>");

                        out.print("Education: " + request.getParameter("education"));

                        out.close();

 

                } catch (Exception e) {

                        System.out.println(e);

                }

        }

}

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:web="https://xmlns.jcp.org/xml/ns/javaee">

  <servlet>

    <servlet-name>s1</servlet-name>

    <servlet-class>com.java4coding.FirstServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>s1</servlet-name>

    <url-pattern>/servlet1</url-pattern>

  </servlet-mapping>

  <servlet>

    <servlet-name>s2</servlet-name>

    <servlet-class>com.java4coding.SecondServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>s2</servlet-name>

    <url-pattern>/servlet2</url-pattern>

  </servlet-mapping>

  <servlet>

    <servlet-name>s3</servlet-name>

    <servlet-class>com.java4coding.ThirdServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>s3</servlet-name>

    <url-pattern>/servlet3</url-pattern>

  </servlet-mapping>

</web-app>

 

Output

 

servlet-cookie-2
 

All Chapters
Author