Deleting Cookie

Deleting Cookie


Posted in : Servlet Posted on : November 10, 2010 at 5:51 PM Comments : [ 0 ]

This section contains the details about the Deleting Cookie using servlet in java

Deleting Cookie

A cookie has values in the form of name/value pairs. For example, a cookie can have a name, user with the value, Ankit. They are created by the server and are sent to the client with the HTTP response headers. The client saves the cookies in the local hard disk and sends them along with the HTTP request headers to the server.

A cookie can be remove by invoking the following function :

cookie.setMaxAgeZero(0);

Here 'cookie' is the created object & it's name can be different. By setting setMaxAge() function value to zero, the cookie specified will be deleted automatically.

By setting it's age to zero using 'setMaxAge()' method, it will not actually remove cookie. It just remove the value or attribute it contains.

Given below the code which removes the cookie's attribute or value not cookie :

package devmanuals;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;

public class DeleteCookie extends HttpServlet {
PrintWriter pw = null;

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

doPost(req, res);
}

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

pw = res.getWriter();
String username = null;
// Retrieve the cookies, if any, stored in the client browser
Cookie ck[] = req.getCookies();
if (ck != null) {
for (int i = 0; i < ck.length; i++) {
if (ck[i].getName().equals("user")) {
// Retrieve username from the cookie
ck[i].setMaxAge(0);
res.setContentType("text/html");
pw.println("Cookie is deleted");
}

}
} else {

pw.println("No cookies found");
}
}
}

Output :

Download Source Code 

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics