servlets - 为什么带有空格的 cookie 值会带引号到达客户端?

标签 servlets cookies encoding

我是一名 .NET 开发人员,开始涉足 Java。

在 .NET 中,我可以将 cookie 的值设置为包含空格的字符串:new HttpCookie("myCookieName", "my value") - 当我在客户端 (JavaScript) 读取该值时,我得到了我期望的值(我的值)。

如果我在 Java servlet 中做同样的事情 - new Cookie("myCookieName", "my value") ,我得到的值包括双引号(“我的值(value)”)。

为什么会有差异?我错过了什么吗?人们如何在 Java 世界中处理这个问题?您是否对值进行编码,然后在客户端进行解码?

最佳答案

当您使用以下值之一设置 cookie 值时,如 Cookie#setValue() 中所述,

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.



那么平均容器将隐式地将 cookie 设置为版本 1 ( RFC 2109 spec ) 而不是默认版本 0 ( Netscape spec )。该行为不是由 Servlet API 指定的,容器可以自由地实现它(例如,它可能会抛出一些 IllegalArgumentException )。据我所知,Tomcat、JBoss AS 和 Glassfish 在隐式更改 cookie 版本方面的行为都是一样的。至少对于 Tomcat 和 JBoss AS,这是修复 this security issue 的结果。 .

版本 1 cookie 如下所示:
name="value with spaces";Max-Age=3600;Path=/;Version=1

while a version 0 compatible cookie look like this:

name=value%20with%20spaces;Expires=Mon, 29-Aug-2011 14:30:00 GMT;Path=/

(note that an URL-encoded value is valid for version 0)

Important note is that Microsoft Internet Explorer doesn't support version 1 cookies. Even not the current IE 11 release. It'll interpret the quotes being part of the whole cookie value and will treat and return that accordingly. It does not support the Max-Age attribute and it'll ignore it altogether which causes that the cookie's lifetime defaults to the browser session. You was apparently using IE to test the cookie handling of your webapp.

To support MSIE as well, you really need to URL-encode and URL-decode the cookie value yourself if it contains possibly characters which are invalid for version 0.

Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
// ...


String value = URLDecoder.decode(cookie.getValue(), "UTF-8"));
// ...

为了支持面向全局受众的版本 1 cookie,您将真正等待 Microsoft 修复缺少 MSIE 支持的问题,并且带有修复程序的浏览器已成为主流。换句话说,这需要很长时间(更新:截至目前,5 年后,它似乎永远不会发生)。同时,您最好坚持使用版本 0 兼容的 cookie。

关于servlets - 为什么带有空格的 cookie 值会带引号到达客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/572482/

相关文章:

java - 当 cookie 包含变音字符时 Tomcat 7 异常

java - 我如何将网站与 Optaplanner(html、javascript、php)集成?

java - 如何根据用户登录隐藏某些功能?

java - 如何识别调用Web服务的应用程序

java - 在 tomcat servlet 例程中使用异步 HTTP 客户端更好吗?

javascript - 如何使用cookie中保存的URL?

google-chrome - Chrome 和 Firefox 未清除 JSESSIONID cookie 会导致重定向循环

html - HTML 源代码中的这些奇怪字符是什么?

java - 显示时字符发生变化 - 意大利和波兰的字符集问题

c# - 我的应用程序的内部编码