11月25日学习日志

今天学习了jsp删除cookie。

删除 cookie 非常简单。如果您想要删除一个 cookie,按照下面给的步骤来做就行了:

获取一个已经存在的 cookie 然后存储在 Cookie 对象中。

将 cookie 的有效期设置为 0。

将这个 cookie 重新添加进响应头中。

下面的程序删除一个名为 "name" 的 cookie,当您第二次运行 cookie.jsp时,name 将会为 null。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>获取 Cookie</title>
</head>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // 获取当前域名下的cookies,是一个数组
   cookies = request.getCookies();
   if( cookies != null ){
      out.println("<h2> 查找 Cookie 名与值</h2>");
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         if((cookie.getName( )).compareTo("name") == 0 ){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("删除 Cookie: " + 
            cookie.getName( ) + "<br/>");
         }
         out.print("参数名 : " + cookie.getName());
         out.print("<br>");
         out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") +" <br>");
         out.print("------------------------------------<br>");
      }
  }else{
      out.println("<h2>没有发现 Cookie</h2>");
  }
%>
</body>
</html>

 

posted @ 2020-11-25 18:55  张笑天  阅读(45)  评论(0编辑  收藏  举报