如何创建不带引号的 cookie 值? [英] How to create cookie without quotes around value?

查看:36
本文介绍了如何创建不带引号的 cookie 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用电子邮件地址作为值创建 cookie - 但是当我尝试 - 然后我有结果:

I need to create cookie with e-mail address as value - but when I try to - then I have result:

someone@example.com"

"someone@example.com"

但我想要:

someone@example.com

someone@example.com

创建 cookie 时不应使用双引号 - 因为其他应用程序以这种格式使用它.如何强制java不添加双引号?Java 添加它们是因为有特殊字符at".

The cookie should be created without double quoted marks - because other application uses it in such format. How to force java to not to add double quoted? Java adds them because there is special char "at".

我以这种方式创建 cookie:

I create the cookie that way:

    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    Cookie cookie = new Cookie("login", "someone@example.com");
    cookie.setMaxAge(2592000);
    cookie.setDomain("domain.com");
    cookie.setVersion(1);
    response.addCookie(cookie);

感谢您的帮助.

推荐答案

确实是由 @ 符号引起的.这是不允许的 在版本 0 cookie 中.容器将隐式强制它成为版本 1 cookie(在 MSIE 浏览器中会中断).您想要URL 编码cookie 创建时的 cookie 值

It's indeed caused by the @ sign. This is not allowed in version 0 cookies. The container will implicitly force it to become a version 1 cookie (which breaks in MSIE browsers). You'd like to URL-encode the cookie value on cookie's creation

Cookie cookie = new Cookie("login", URLEncoder.encode("someone@example.com", "UTF-8"));
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
response.addCookie(cookie);

URL 解码饼干阅读

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

请注意,您一定不要将 cookie 版本明确设置为 1.

Note that you should for sure not explicitly set the cookie version to 1.

与具体问题无关,最终用户或中间人可以看到和操纵 cookie.在 cookie 中携带电子邮件地址是一种难闻的气味.如果最终用户将其更改为不同的地址怎么办?您认为通过在 cookie 中携带电子邮件地址来解决的任何功能需求(记得登录?)很可能应该以不同的方式解决.

Unrelated to the concrete problem, cookies are visible and manipulatable by the enduser or man-in-the-middle. Carrying the email address around in a cookie is a bad smell. What if the enduser changes it to a different address? Whatever functional requirement (remembering the login?) you thought to solve with carrying the email address around in a cookie should most likely be solved differently.

这篇关于如何创建不带引号的 cookie 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆