Home Tutorial Java Jsp Deleting Cookie in JSP


Share on Google+Share on Google+
Deleting Cookie in JSP
Posted on: June 26, 2010 at 12:00 AM
In this section, we will discuss about deleting cookies in JSP with an example.

Deleting Cookie in JSP

In this section, we will discuss about deleting cookies in JSP with an example.

Cookie class : In JSP , cookie are the object of the class javax.servlet.http.Cookie .A cookie's value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. A Cookie object may be added to an HttpResponse object using HttpResponse.addCookie(). To extract a cookie from an HttpRequest object, you can use HttpRequest.getCookies() , which returns an array of Cookie objects representing all the cookies included in the request.

Example of deleting cookie :

Cookie can be remove by invoking function below:

   cookie.setMaxAge(0) ;

By setting "setMaxAge()" function value to zero, the cookie specified will be deleted automatically.

In this example ,we also invoke function "getMaxAge()" to check whether actually it's value change or not. If you also invoke    "getValue()" method ,after deleting it will not show you anything.


<%@ page language="java" import="java.util.*"%>


String username=request.getParameter("username");

if(username==null) username="";

Date now = new Date();

Cookie cookie = new Cookie ("username",username);

cookie.setMaxAge(365 * 24 * 60 * 60);





<title>Saving Cookie</title>






<h2><font color="blue">Cookie Age is set to zero..Output of <code>cookie.getMaxAge() --</code></font>


<h3><font color="red">Cookie is deleted automatically by setting it's value to zero</font></h3>




Download Source Code


Related Tags for Deleting Cookie in JSP :

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: June 26, 2010

Recommend the tutorial

Advertisements Advertisements