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
HttpResponse object using
To extract a cookie from an
HttpRequest object, you can use
, 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:
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.*"%>
Date now =new Date();
Cookie cookie =new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
<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>
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.