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

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

问题描述

在Java Servlet中,如何更改现有Cookie的值?在HttpServletResponse中有一个addCookie方法,但没有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,路径和域名,默认。

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天全站免登陆