Cookie Version in J2EE

Cookie Version in J2EE

原文章:http://villadora.me/2014/05/06/cookie-version/

在处理Cookie的时候发现不能处理servlet request中不能获取cookie中的带”:”字符的值.

Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        if (StringUtils.equalsIgnoreCase(cookie.getName(), name)) {
            value = cookie.getValue(); // if the value in cookie is 'http://example.com' then here it will get 'http'
            break;
        }
    }
}

 

这是因为目前Cookie有两个标准,一个是Version 0 (Netscape spec)

而J2EE的实现描述 Cookie#setValue 中

1
2
With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.
`

也就是说Version 0 是不能包含空格,括弧,等号,逗号, 双引号等字符的。

而Version 1 (RFC 2109 spec) 是可以的。

但是javax.servlet.http.Cookie的实现时默认是使用 Version 0

1
2
By default, cookies are created according to the Netscape cookie specification. The version can be changed with the
setVersion method.

而看起来container默认的选择也是使用了Version 0而没有去改变version。所以当Cookie值中带有’:’时,就无法读到colon后的内容。

如果没有办法改container并且只能使用默认的request的话,暂时的解决方案是在写cookie的时候URLEncode, 然后在服务器端读的时候做URLDecode

posted on 2014-06-04 10:29  dvilla  阅读(302)  评论(0编辑  收藏  举报

导航