Java 怎么从servlet根据名称及其默认路径“/”删除cookie

2019年8月16日22:12:42 评论 24

1.简介

Java 怎么从servlet根据名称及其默认路径“/”删除cookie?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Main{
    
    public static void removeCookie(String name) {
        setCookie(name, "__deleted__", 0, "/");
    }
    
    public static void removeCookie(String name, String path) {
        setCookie(name, "__deleted__", 0, path);
    }
    
    public static void setCookie(String name, String value,
            int maxAgeInSeconds) {
        setCookie(name, value, maxAgeInSeconds, "/");
    }
    
    public static void setCookie(String name, String value,
            int maxAgeInSeconds, String path) {
        HttpServletResponse response = ActionContext.getActionContext()
                .getHttpServletResponse();
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setPath(path);
        response.addCookie(cookie);
    }
}

 

3.总结

示例代码演示了 Java 怎么从servlet根据名称及其默认路径“/”删除cookie,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: