Send Cookies in Servlets

This section illustrates you how to send cookie in servlets.

Send Cookies in Servlets


This section illustrates you how to send cookie in servlets.

Cookies are small bits of  information that a Web server sends to a browser and that the browser returns unchanged after visiting the same page. A Class javax.servlet.http.Cookie, represents the cookie. HttpservletRequest and HttpServletResponse interfaces have methods for getting and setting the cookies. You can create cookie, read cookie and send cookie to the client browser. You can create cookie by calling the cookie Constructor. 

To read cookies, call request.getCookies() method which returns an array of cookie objects. To send cookie, a servlet create cookie and add the cookie to the response header with method response.addCookie(cookie).

Here is the code of

import javax.servlet.*;
import javax.servlet.http.*;
public class SendCookie extends HttpServlet
public void doGet( HttpServletRequest req, HttpServletResponse res )
 throws IOException{
 int var, i ;
 String s ;
 Cookie [] cookie = req.getCookies() ;
 Cookie countCookie = null ;
 for( i = 0; i < cookie.length; i++ ){
  if( cookie[i].getName().equals("Mycookie") ){
 countCookie = cookie[i] ;
  if( countCookie != null ){
  s = countCookie.getValue() ;
  if( s != null ){
  var = Integer.parseInt( s ) ;
  var = 0 ;
  countCookie = new Cookie( "Mycookie", null ) ;
 }catch( IllegalArgumentException exception ){}
 var = 0 ;
  var++ ;
  Integer oI = new Integer( var ) ;
 countCookie.setValue( oI.toString() ) ;
  res.addCookie( countCookie ) ;
  PrintWriter out = res.getWriter() ;
  out.write( "You've visited the page" +  var+ " times" ) ;


Now in the above example which shows the process of adding and removing cookies. With the method  req.getCookies(), you will get all the cookies on request. 

When you run the program you will get the following output.

Here is the output

After refreshing the browser , value will change. Here is the output after refreshing the page:

Download Source Code


Share on Google+Share on Google+

Send Cookies in Servlets

Posted on: July 19, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Send Cookies in Servlets  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
August 31, 2011