Deleting Cookie in JSP


 

Deleting Cookie in JSP

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

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.

deletecookie.jsp

<%@ 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);

response.addCookie(cookie);

%>

<html>

<head>

<title>Saving Cookie</title>

</head>

<body>

<%

cookie.setMaxAge(0);

%>

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

<%out.println(cookie.getMaxAge());%></h2>

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

</body>

0

</html>

OUTPUT :

1

Download Source Code

Ads