在 Java Servlet 中,如何更改现有 cookie 的值? [英] In a Java Servlet how can I change the value of an existing cookie?

查看:41
本文介绍了在 Java Servlet 中,如何更改现有 cookie 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java Servlet 中,如何更改现有 cookie 的值?有 addCookie 方法,但 HttpServletResponse 中没有 deleteCookie 或 editCookie

In a Java Servlet how can I change the value of an existing cookie? There is an addCookie method, but no deleteCookie or editCookie in HttpServletResponse

推荐答案

那些确实不存在.只需自己创建实用方法即可.尤其是获取想要的 cookie 实在是太臃肿了.例如

Those indeed don't exist. Just create utility methods yourself which do that. Particularly getting the desired cookie is quite bloated. E.g.

public final class Servlets {

    private Servlets() {}

    public static Cookie getCookie(HttpServletRequest request, String name) {
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }

        return null;
    }

}

要编辑 cookie,请设置其值,然后将其添加到响应中:

To edit a cookie, set its value and then add it to the response:

Cookie cookie = Servlets.getCookie(request, "foo");

if (cookie != null) {
    cookie.setValue(newValue);
    response.addCookie(cookie);
}

如有必要,设置 maxage、path 和 domain(如果它们与您的默认值不同).客户端即不会将此信息发回.

Set if necessary the maxage, path and domain as well if they differs from your default. The client namely doesn't send this information back.

要删除 cookie,请将最大年龄设置为 0(最好将值也设置为 null):

To delete a cookie, set the max age to 0 (and preferably also the value to null):

Cookie cookie = Servlets.getCookie(request, "foo");

if (cookie != null) {
    cookie.setMaxAge(0);
    cookie.setValue(null);
    response.addCookie(cookie);
}

如有必要,设置路径和域,如果它们与您的默认值不同.客户端即不会将此信息发回.

Set if necessary the path and domain as well if they differs from your default. The client namely doesn't send this information back.

这篇关于在 Java Servlet 中,如何更改现有 cookie 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆