如何用JSP删除Cookie?
删除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;
// Get an array of Cookies associated with the this domain
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
现在再次运行 https://:8080/main.jsp ,它应该只显示一个Cookie,如下所示 -
Found Cookies Name and Value Name : last_name, Value: Player
你可以在Internet Explorer中手动删除Cookie。从“工具”菜单开始并选择“Internet选项”。要删除所有Cookie,请单击“删除Cookie”按钮。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
JavaScript
PHP