Cookie in servlet

Cookie:

A cookie is a small piece of information as a text file stored on client’s machine by a web application.

How cookie works?

As HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every new request. In case of cookie a text file with small piece of information is added to the response of first request. They are stored on client’s machine. Now when a new request comes cookie is by default added with the request. With this information we can identify that it is a new user or a previous user.

Types of cookies:

1. Session cookies/Non-persistent cookies: These types of cookies are session dependent i.e. they are accessible as long as session is open and they are lost when session is closed by exiting from the web application.

2. Permanent cookies/Persistent cookies: These types of cookies are session independent i.e. they are not lost when session is closed by exiting from the web application. They are lost when they expire.

Advantages of cookies:

  1. They are stored on client side so don’t need any server resource.
  2. Easy technique for session management.

Disadvantages of cookies:

  1. Cookies can be disabled from the browser.
  2. Security risk is there because cookies exist as a text file so any one can open and read user’s information.

Cookie Class:

Cookie class provides the methods and functionality for session management using cookies. Cookie class is in javax.servlet.http

Package javax.servlet.http.Cookie.

Commonly used constructor of Cookie class:

1. Cookie(String name,String value): Creates a cookie with specified name and value pair.
Syntax:

public Cookie(String name,String value)

Commonly used methods of cookie class:

1. setMaxAge(int expiry):Sets the maximum age of the cookie.
Syntax:

public void setMaxAge(int expiry)

2. getMaxAge(): Returns the maximum age of the cookie. Default value is -1.
Syntax:

public int getMaxAge()

3. setValue(String newValue): Change the value of the cookie with new value.
Syntax:

public void setValue(String newValue)

4. getValue(): Returns the value of the cookie.
Syntax:

public String getValue()

5. getName(): Returns the name of the cookie.
Syntax:

public String getName()

How to create cookie?

HttpServletResponse interface’s addCookie(Cookie ck) method is used to add a cookie in response object.

Syntax: public void addCookie(Cookie ck)

Example:

//create cookie object  

Cookie cookie=new Cookie(“cookieName”,”cookieValue”);

//add cookie object in the response

response.addCookie(cookie);

 

How to get cookie?

HttpServletRequest interface’s getCookies() method is used to get the cookies from request object.

Syntax: public Cookie[] getCookies()

Example:

//get all cookie objects.

Cookie[] cookies = request.getCookies();

//iterate cookies array to get individual cookie objects.

for(Cookie cookie : cookies){

            out.println(“Cookie Name: ” + cookie.getName());

            out.println(“Cookie Value: ” + cookie.getValue());

}

 

How to remove or delete cookies?

Cookies can be removed by setting its expiration time to 0 or -1. If expiration time set to 0 than cookie will be removed immediately. If expiration time set to -1 than cookie will be removed when browser closed.

Example:

//Remove value from cookie

Cookie cookie = new Cookie(“cookieName”, “”);

//Set expiration time to 0.

cookie.setMaxAge(0);

//add cookie object in the response.

response.addCookie(cookie);

 

Session management example using cookie:

CreateCookieServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is used to create cookies.
 * @author W3schools360
 */
public class CreateCookieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    //no-argument constructor
    public CreateCookieServlet() {
        
    }

    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response)
                 throws ServletException, IOException {
    response.setContentType("text/html"); 
        PrintWriter out = response.getWriter();
        
        //get parameters from request object.
        String userName = request.getParameter("userName").trim();
        String password = request.getParameter("password").trim();
        
        //check for null and empty values.
        if(userName == null || userName.equals("") || 
                password == null || password.equals("")){
            out.print("Please enter both username " +
                    "and password. <br><br>");
            RequestDispatcher requestDispatcher = 
                request.getRequestDispatcher("/login.html");
            requestDispatcher.include(request, response);
        }//Check for valid username and password.
        else if(userName.equals("jai") && password.equals("1234")){
            //create cookie objects.
            Cookie cookie1 = new Cookie("userName",userName);
            Cookie cookie2 = new Cookie("password",password);
            //add cookie in the response object.
            response.addCookie(cookie1);
            response.addCookie(cookie2);
            out.print("<h3>Cookies are created. Click on the " +
                    "below button to get cookies."); 
          out.print("<form action="GetCookieServlet" method="POST">");  
                out.print("<input type="submit" value="Get Cookie">");  
                out.print("</form>");  
                  
                out.close();  
        }else{
            out.print("Wrong username or password. <br><br>");
            RequestDispatcher requestDispatcher = 
                request.getRequestDispatcher("/login.html");
            requestDispatcher.include(request, response);
        }
    }    
}

 

GetCookieServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is used to get cookies.
 * @author W3schools360
 */
public class GetCookieServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;
       
    //no-argument constructor
    public GetCookieServlet() {
        
    }

    protected void doPost(HttpServletRequest request, 
        HttpServletResponse response)
                      throws ServletException, IOException {
    response.setContentType("text/html"); 
        PrintWriter out = response.getWriter();
        
        try{
           Cookie cookies[] = request.getCookies();
           for(Cookie cookie : cookies){
            out.println("Cookie Name: " + cookie.getName());
            out.println("Cookie Value: " + cookie.getValue());
            out.println("");
            }
            
          out.println("Click on the below button to delete cookies.");
          out.print("<form action="DeleteCookieServlet" method="POST">");
          out.print("<input type="submit" value="Delete Cookies">");
          out.print("</form>");
          out.close();  
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

 

DeleteCookieServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is used to delete cookies.
 * @author W3schools360
 */
public class DeleteCookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	//no-argument constructor
    public DeleteCookieServlet() {
        
    }

    protected void doPost(HttpServletRequest request, 
	   HttpServletResponse response)
	                throws ServletException, IOException {
	response.setContentType("text/html"); 
    	PrintWriter out = response.getWriter();
    	
    	try{
    		Cookie cookies[] = request.getCookies();
    		out.print("Deleted cookie are:");
    		for(Cookie cookie : cookies){
    		   cookie.setMaxAge(0);
    		   out.println("Cookie name: " + cookie.getName());
    	        }
    	    
    	    out.close();  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
     }
}

login.html

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>


    <form action="CreateCookieServlet" method="post">
        Username:<input type="text" name="userName">
                <br><br>
        Password:<input type="password" name="password">
                <br><br> 
        <input type="submit" value="login"> 
    </form>

 

web.xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
  <servlet>
    <servlet-name>CreateCookieServlet</servlet-name>
    <servlet-class>
           com.w3schools.business.CreateCookieServlet
    </servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>CreateCookieServlet</servlet-name>
    <url-pattern>/CreateCookieServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>GetCookieServlet</servlet-name>
    <servlet-class>
        com.w3schools.business.GetCookieServlet
    </servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>GetCookieServlet</servlet-name>
    <url-pattern>/GetCookieServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>DeleteCookieServlet</servlet-name>
    <servlet-class>
        com.w3schools.business.DeleteCookieServlet
    </servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>DeleteCookieServlet</servlet-name>
    <url-pattern>/DeleteCookieServlet</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
  
</web-app>