如何使用 JSP 删除 cookie?
jspjava 8object oriented programmingprogramming
删除 cookie 非常简单。如果您想删除 cookie,那么您只需按照以下三个步骤 −
读取已经存在的 cookie 并将其存储在 Cookie 对象中。
使用 setMaxAge() 方法将 cookie 年龄设置为零以删除现有 cookie。
将此 cookie 重新添加回响应标头。
以下示例将向您展示如何删除名为 "first_name" 的现有 cookie,当您下次运行 main.jsp JSP 时,它将返回 first_name 的空值。
示例
<html> <head> <title>读取 Cookies</title> </head> <body> <center> <h1>读取 Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // 获取与此域关联的 Cookies 数组 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,请单击"删除 Cookie"按钮。