In this page , you will learn important line
  • What is a cookie?
  • How Cookie works ?
  • Why is the need of cookie in servlet?
  • What are the types of cookie?
  • What are the limitations of cookie?

Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.This token contains some information of the client in the form of key-value pair.

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. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.


How Cookie works ?

Every request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the correct browser. After that if request is sent by the user or client, cookie is added with request by default. Thus, we recognize the user as the old user.

cookies in servlet

Cookies API

Treats are made utilizing Cookie class present as a part of Servlet API. Treats are added to reaction object utilizing the addCookie() method . This system sends treat data over the HTTP reaction stream. getCookies() method is utilized to get to the treats that are added to response object


 Cookie ck =new Cookie ("username",name);
  ck.setMaxAge(30*50);
 response.addCookie(ck);
 Cookie[] cks=request.getCookies();
 

How to create Cookie?

 Cookie c=new Cookie("user","Mithilesh kushwaha");//creating cookie object 
response.addCookie(c);//adding cookie in the response 

How to delete Cookie?

It is mainly used to logout or signout the user.

 Cookie c=new Cookie("user","");//deleting value of cookie 
c.setMaxAge(0);//changing the maximum age to 0 seconds 
response.addCookie(c);//adding cookie in the response 

How to get Cookies?

 
 Cookie c[]=request.getCookies(); 
for(int i=0;i<c.length;i++){ 
out.print(" "+c[i].getName()+" "+c[i].getValue());//printing name and value of cookie 
} 

Example usage of Cookies

cookies in servlet

Below mentioned files are required for the example:

 
<form method="post" action="validate">
  Name:<input type="text" name="user" /><br/>
  Password:<input type="text" name="pass" ><br/>
  <input type="submit" value="submit">
</form>

web.xml

 
<web-app...>
    
    <servlet>
        <servlet-name>validate</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
        <servlet-name>validate</servlet-name>
        <url-pattern>/validate</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    
</web-app>

MyServlet.java

 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        
        if(pass.equals("1992"))
        {
            Cookie ck = new Cookie("username",name);
            response.addCookie(ck);
            response.sendRedirect("First");
        }
    }
}

First.java

 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cks = request.getCookies();
        out.println("Welcome "+cks[0].getValue());
    }
}

Types of Cookie

There are 2 types of cookies in servlets.

  • Non-persistent cookie
  • Persistent cookie

Advantage of Cookies

  • Simplest technique of maintaining the state.
  • Cookies are maintained at client side

Disadvantage of Cookies

  • It will not work if cookie is disabled from the browser.
  • Only textual information can be set in Cookie object.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies

Constructor of Cookie class

Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.