Servlet课程0426(十)Servlet如何删除cookie

时间:2023-10-01 14:46:26
//如何删除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 = ;
//如果allCookie不为空
if(allCookies != null)
{
//从中取出cookie
for (i = ; i<allCookies.length; i++)
{
//依次取出
Cookie temp = allCookies[i]; if(temp.getName().equals("color1"))
{
//将该cookie删除,设置等于0这个cookie就被删除了
temp.setMaxAge();
pw.println("删除了color这个cookie");
break;
}
}
} }
catch(Exception ex)
{
ex.printStackTrace();
} } //处理get请求
//req用于获得客户端(浏览器)的信息
//res用于向 客户端(浏览器)返回信息
public void doPost(HttpServletRequest req, HttpServletResponse res)
{ this.doGet(req,res); } }