[英]How to generate identical cookies from Java and from Javascript (without enclosing double-quotes)
I try to make a cookie's value generated from the server side (in Java) identical to a cookie's value generated from this jquery's cookies librarie , which use : 我试图使从服务器端(在Java中)生成的cookie值与从此jquery的cookie librarie生成的cookie值相同,后者使用:
encodeURIComponent( value )
to encode the cookie value. 对Cookie值进行编码。
Let's take this example string : 让我们来看这个示例字符串:
a b,c;d*~'"()!±
I use this code , in Java, to encode a cookie value : 我在Java中使用以下代码对Cookie值进行编码:
String result = URLEncoder.encode(str, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
I then add the cookie to the response : 然后,我将cookie添加到响应中:
Cookie cookie = new Cookie("testCookieServerSide", encodeValue("a b,c;d*~'\"()!±"));
response.addCookie(cookie);
This adds double-quotes around the value! 这会在值周围添加双引号! :
:
"a%20b%2Cc%3Bd*~'%22()!%C2%B1"
When encoding the same value using the jquery library, I get the same value but without the double-quotes : 当使用jquery库编码相同的值时,我得到相同的值,但没有双引号:
a%20b%2Cc%3Bd*~'%22()!%C2%B1
Is it possible to tell Java to not generate the double-quotes? 是否可以告诉Java 不生成双引号? I've heard of cookie.setVersion(0) or cookie.setVersion(1) but this doesn't seem to change anything.
我听说过cookie.setVersion(0)或cookie.setVersion(1),但这似乎没有任何改变。
When retrieving those two values on the server-side, they are identical after a : 在服务器端检索这两个值时,它们在a之后是相同的:
URLDecoder.decode(cookie.getValue(), "UTF-8");
... the double-quotes are removed. ...删除双引号。 Great.
大。
But on the client side, the two values are differents ! 但是在客户端, 这两个值是不同的 !
alert($.cookies.get('testCookieServerSide')); => "a b,c;d*~'"()!±"
alert($.cookies.get('testCookieClientSide')); => a b,c;d*~'"()!±
Any idea on how to generate the exact same value? 关于如何产生完全相同的值的任何想法吗? How do you deal with this?
您如何处理?
Here's the fix I found : 这是我发现的解决方法:
I didn't find any way to tell Java to stop adding those double-quotes, so I have to live with them. 我没有找到任何方法告诉Java停止添加这些双引号,因此我必须忍受它们。
I modified the jquery's cookies library I use, so instead of decoding the cookie value like this : 我修改了我使用的jquery的cookie库 ,所以不要像这样解码cookie值:
value = decodeURIComponent( pair[1] );
It uses: 它用:
value = decodeURIComponent( pair[1].replace( /^"(.*)"$/, '$1' ) );
When this line of code is reached, the value in the cookie is still encoded (the js library itself encode it on the client-side and I encode it using Java on the server-side, using the above code). 当到达这行代码时,cookie中的值仍然会被编码(js库本身在客户端对它进行编码,而我使用上述代码在服务器端使用Java对其进行编码)。 So the double-quotes, at the begining and end of the value, if not encoded, are necessarily characters added by Java ... They have to be removed when getting the value.
因此,值的开头和结尾的双引号(如果未编码) 一定是Java添加的字符 。在获取值时必须将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.