Use of Cookie in Servlet

he cookie class provides an easy way for servlet to read, create, and manipulate HTTP-style cookies, which allows servlets to store small amount of data.

Use of Cookie in Servlet

Use of Cookie in Servlet

     

This section illustrates you  how cookie is used in Servlet.

The cookie class provides an easy way  for servlet to read, create, and manipulate HTTP-style cookies, which allows  servlets to store small amount of data. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site.

A servlet uses the getCookies() method of HTTPServletRequest to retrieve cookies as request. The addCookie() method of HTTPServletResponse sends a new cookie to the browser. You can set the age of cookie by setMaxAge() method.

Here is the code which  defines cookie and shows how to set the maximum age of cookie.

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

public class UseCookies extends HttpServlet { 
  public void doGet ( HttpServletRequest request,
    HttpServletResponse response )
throws ServletException, IOException {
  PrintWriter out;
  response.setContentType("text/html");
  out = response.getWriter();
  Cookie cookie = new Cookie("CName","Cookie Value");
  cookie.setMaxAge(100);
  response.addCookie(cookie);
  
  out.println("<HTML><HEAD><TITLE>");
  out.println(" Use of cookie in servlet");
  out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
  out.println(" <b>This is a Cookie example</b>");
  out.println("</BODY></HTML>");
  out.close();
  }
}

In the above example, a servlet class UseCookies defines the cookie class. Here  the age of cookie has been set as
setMaxAge(100). If its value is set to 0, the cookie will delete immediately. After the time provided been expired, cookie will automatically deleted.

Here is the output

Download Source Code