java4all@1986 java. Powered by Blogger.

Uses Of Cookie in Servlets?

>> Monday, June 13, 2011

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.
The below code shows how to set maximum Age 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.

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP