Servlet 3.1 删除 Cookie
Java Servlet 删除 Cookie 是非常简单的
删除一个 cookie,只需要按照以下三个步骤进行:
- 读取一个现有的 cookie,并把它存储在 Cookie 对象中
- 使用 setMaxAge() 方法设置 cookie 的存活时间为 0 ,来删除现有的 cookie
- 把这个 cookie 添加到响应头
范例
下面的范例将删除现有的名为 "url" 的 cookie
下一次读取 Cookie url 的值将返回 null
// author: 简单教程(www.twle.cn) // Copyright © 2015-2065 www.twle.cn. All rights reserved. package cn.twle.demo; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.WebServlet;; import java.util.Calendar; import java.util.GregorianCalendar; @WebServlet(name = "DeleteCookieServlet", urlPatterns = {"delete_cookie"}, loadOnStartup = 1) public class DeleteCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // 获取与该域相关的 Cookie 的数组 cookies = request.getCookies(); // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "删除 Cookie 范例 | 简单教程(www.twle.cn)"; String docType = "<!DOCTYPE html>\n"; out.println(docType + "<title>" + title + "</title>" + "<p>" + title +"</p>" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<p>Cookie 名称和值</p>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("url") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("已删除的 cookie:" + cookie.getName( ) + "<br/>"); } out.print("名称:" + cookie.getName( ) + ","); out.print("值:" + cookie.getValue( )+" <br/>"); } }else{ out.println( "<p style=\"color:red\">No Cookie founds</h2>"); } } }
在浏览器上输入 http://localhost:8080/servlet/delete_cookie 显示结果如下