删除Cookie非常简单。如果您要删除Cookie,则只需执行以下三个步骤-
读取一个已经存在的cookie并将其存储在Cookie对象中。
使用setMaxAge()方法将cookie年龄设置为零,以删除现有的cookie。
将此Cookie重新添加到响应标头中。
下面的示例将向您展示如何删除一个名为“ first_name”的现有cookie,并且当您下次运行main.jsp JSP时,它将为first_name返回null值。
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
//获取与此域名关联的Cookie数组
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>现在让我们将上面的代码放入main.jsp文件中,然后尝试访问它。它将显示以下结果-
输出结果
Cookies Name and Value Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player
现在再次运行http:// localhost:8080 / main.jsp ,它应该仅显示一个cookie,如下所示-
Found Cookies Name and Value Name : last_name, Value: Player
您可以在Internet Explorer中手动删除Cookie。从“工具”菜单开始,然后选择“ Internet选项”。要删除所有cookie,请单击Delete Cookies按钮。