//如何删除Cookie案例 package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class CookieTest3 extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) { try{ //解决中文乱码 res.setCharacterEncoding("gbk"); PrintWriter pw = res.getWriter(); //客户端得到所有cookie信息 Cookie[] allCookies = req.getCookies(); int i = 0; //如果allCookie不为空 if(allCookies != null) { //从中取出cookie for (i = 0; i<allCookies.length; i++) { //依次取出 Cookie temp = allCookies[i]; if(temp.getName().equals("color1")) { //将该cookie删除,设置等于0这个cookie就被删除了 temp.setMaxAge(0); pw.println("删除了color这个cookie"); break; } } } } catch(Exception ex) { ex.printStackTrace(); } } //处理get请求 //req用于获得客户端(浏览器)的信息 //res用于向 客户端(浏览器)返回信息 public void doPost(HttpServletRequest req, HttpServletResponse res) { this.doGet(req,res); } }
时间: 2024-12-28 21:40:18