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 SendCookie.java
import java.io.*;
import java.io.IOException;
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 ) ;
}
else{
var = 0 ;
}
}
else{
try{
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

|