java 如何更新 JSP 中现有的 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5093250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:23:30  来源:igfitidea点击:

How do you update an existing cookie in JSP?

javajspcookies

提问by James Sumners

I have a cookie, myCookie, that contains a hash value. This cookie is set to expire in one year and has a path of '/'. I need to update this cookie with a new hash value. When my JSP script is loaded I retrieve the cookie like so:

我有一个myCookie包含哈希值的 cookie 。此 cookie 设置为一年后过期,路径为“/”。我需要用新的哈希值更新这个 cookie。当我的 JSP 脚本加载时,我像这样检索 cookie:

Cookie[] cookies = request.getCookies();
Cookie myCookie = null;

for (int i = 0; i < cookies.length; i += 1) {
  if (cookies[i].getName().equals("myCookie")) {
    myCookie = cookies[i];
    break;
  }
}

After determining that the value of the cookie needs to be updated, I do the following to update it:

在确定需要更新cookie的值后,我执行以下操作来更新它:

myCookie.setValue("my new value");
response.addCookie(myCookie);

Examining the results, I now have two instances of myCookie: the original version with the correct expiration date and path, and the old, invalid, value; and a new cookie named "myCookie" that expires at the end of the session, with the correct value, and a path of the JSP document.

检查结果,我现在有两个实例myCookie:具有正确到期日期和路径的原始版本和旧的无效值;以及一个名为“myCookie”的新 cookie,它在会话结束时过期,具有正确的值和 JSP 文档的路径。

If I do:

如果我做:

myCookie.setValue("my new value");
myCookie.setPath(myCookie.getPath());
myCookie.setMaxAge(myCookie.getMaxAge());
response.addCookies(myCookie);

The samething happens. I get two cookies with the same name and different properties.

同样的事情发生了。我得到两个具有相同名称和不同属性的 cookie。

Does a Cookie object not retain the properties from when it was retrieved? How can I update this cookie?

Cookie 对象是否不保留检索时的属性?我怎样才能更新这个 cookie?

Note:I do not want to modify the path or the expiration date. I only want to update the value of the already set cookie.

注意:我不想修改路径或到期日期。我只想更新已经设置的 cookie 的值。

回答by James Sumners

Per section 3.3.4 of RFC 2965, the user agent does not include the expiration information in the cookie header that is sent to the server. Therefore, there is no way to update an existing cookie's value while retaining the expiration date that was initially set based solely on the information associated with the cookie.

根据RFC 2965 的第 3.3.4 节,用户代理不会在发送到服务器的 cookie 标头中包含到期信息。因此,无法更新现有 cookie 的值,同时保留最初仅根据与 cookie 相关联的信息设置的到期日期。

So the answer to this question is: you can't do that.

所以这个问题的答案是:你不能那样做。

回答by Friendly

Just set the path, ex:

只需设置路径,例如:

cookie.setPath("/");

This should overwrite the old cookie value.

这应该会覆盖旧的 cookie 值。

回答by jt.

If you are manipulating cookies from within a JSP, one thing you will need to watch out for is whether or not the response has already been committed. Once content is written to the output stream, adding a cookie to the response is futile.

如果您在 JSP 中操作 cookie,您需要注意的一件事是响应是否已经提交。将内容写入输出流后,向响应添加 cookie 是徒劳的。

ServletResponseWrapper.isCommitted()

ServletResponseWrapper.isCommitted()

回答by Philipp Hügelmeyer

You can delete the old cookie, if the new one does not contain the same name, path, and domain by setting MaxAge to (0) http://download.oracle.com/javaee/1.3/api/javax/servlet/http/Cookie.html#setMaxAge(int)

您可以通过将 MaxAge 设置为 (0) http://download.oracle.com/javaee/1.3/api/javax/servlet/http来删除旧的 cookie,如果新的 cookie 不包含相同的名称、路径和域/Cookie.html#setMaxAge(int)

回答by Mohammed Shaheen MK

def member = SecUser.get(userService.currentUser().id)
    def cookies = request.getCookies()
    def cookie;
    def sum = 0;
    def cookieSum = 0;
    def cookieItems;
    for(def i=0; i<cookies.size(); i++){
        if (cookies[i].name == 'c17'){
                cookie = cookies[i]
                cookieItems = cookie.value.split('-')
                println "cookieItems......."+cookieItems
                if(params.itemId != null){
                    for(def j=0; j<cookieItems.size(); j++){
                        def oldItem = cookieItems[j].split('\|')[0]
                        if(params.itemId != oldItem){
                            sum = sum + 1
                        }
                    }//Below code for Update your cookie value
                if(sum == cookieItems.size()){
                    cookie.value = cookie.value +"-"+params.itemId+"|"+member.id
                    def b = cookie.value
                    cookie.setValue(b);
                    response.addCookie(cookie);

                }
                }
                break
          }
          else{
             cookieSum = cookieSum + 1
          }

     }
    if ((cookieSum) == cookies.size()){
        // Here ADD new cookie........
         def a = params.itemId+"|"+member.id
         cookie = new Cookie('c17',a.toString())
         cookie.path = '/'
         response.addCookie(cookie)
    }

The Above code can help you for ADD a cookie and UPDATE the cookie value

上面的代码可以帮助您添加 cookie 和更新 cookie 值