Home Servlets Use of Cookie in Servlet
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Use of Cookie in Servlet

Advertisement
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

     

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

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 17, 2008

Ask Questions?    Discuss: Use of Cookie in Servlet  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
chetan
August 23, 2011
servlet

java
Sourabh Sharma
April 14, 2012
Good Job

Wow !!! over the years Rose India has provided such awesome information that i am overwhelmed :) Thank you for being there :)
DMCA.com