从java中的cookie读取电子邮件字符串

发布于 2024-07-08 16:37:32 字数 613 浏览 7 评论 0原文

我的应用程序需要将用户的电子邮件地址存储在 cookie 中,以便我可以预先填充登录表单(用户名 == 电子邮件地址)。 我在 JavaScript 中设置了 cookie 值。 如果我从 JavaScript 读取它,我会得到 [email protected]。 如果我在 Firefox 的 cookie 查看器中查看它,我会得到 [email protected]

然而,当我尝试在 Java 的服务器端读取它时,我只得到 foo

我需要在这里进行某种编码/解码吗? 如果是这样,我该如何以 JavaScript 和 Java 都可以解码的方式做到这一点?

提前致谢! -迈克尔

My application needs to store the users email address in a cookie so that I can pre-populate a login form (username == email address). I set the cookie value in JavaScript. If I read it from JavaScript, I get [email protected]. If I look at it in the cookie viewer in Firefox I get [email protected].

When I try to read it on the server-side in Java however, I only get foo.

Do I need to do some sort of encoding/decoding here? If so, how do I do it in a way that can be decoded by both JavaScript and Java?

Thanks in advance!
-Michael

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

有深☉意 2024-07-15 16:37:32

来自 javax.servlet.http.Cookie doco for setValue(String):

为 cookie 分配一个新值
cookie 已创建。 如果您使用
二进制值,您可能想使用
BASE64 编码。

版本 0
cookie,值不应包含
空格、方括号、圆括号、
等号、逗号、双引号、
斜杠、问号、at 符号
冒号和分号。 空值
可能不会在所有情况下都表现相同
浏览器。

我猜你需要在传入(通过 JavaScript)和传出(通过 Java)时对其进行 BASE64 编码

From the javax.servlet.http.Cookie doco for setValue(String):

Assigns a new value to a cookie after
the cookie is created. If you use a
binary value, you may want to use
BASE64 encoding.

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.

I'm guessing you need to BASE64 encode it on the way in (via JavaScript) and on the way out (via Java)

梦回旧景 2024-07-15 16:37:32

您需要转义 cookie 的值部分。

document.cookie = name + "=" +escape( value ) 
    + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" )
    + ( ( path ) ? ";path=" + path : "" ) 
    + ( ( domain ) ? ";domain=" + domain : "" ) 
    + ( ( secure ) ? ";secure" : "" );

You need to escape the value part of your cookie.

document.cookie = name + "=" +escape( value ) 
    + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" )
    + ( ( path ) ? ";path=" + path : "" ) 
    + ( ( domain ) ? ";domain=" + domain : "" ) 
    + ( ( secure ) ? ";secure" : "" );
-黛色若梦 2024-07-15 16:37:32

我找到了两个解决方案。 这是第一个。

添加回 Base64 编码字符串的填充。 灵感来自 http://fi.am/entry/ urlsafe-base64-encodingdecoding-in-two-lines/

在此解决方案中,JavaScript 保持不变(base64 编码所有内容),服务器端如下所示:

public class CookieDecoder {

private static final Log log = LogFactory.getLog(CookieDecoder.class);

/**
 * @param cookieValue The value of the cookie to decode
 * @return Returns the decoded string
 */
public String decode(String cookieValue) {
    if (cookieValue == null || "".equals(cookieValue)) {
        return null;
    }
    if (!cookieValue.endsWith("=")) {
        cookieValue = padString(cookieValue);
    }
    if (log.isDebugEnabled()) {
        log.debug("Decoding string: " + cookieValue);
    }
    Base64 base64 = new Base64();
    byte[] encodedBytes = cookieValue.getBytes();
    byte[] decodedBytes = base64.decode(encodedBytes);
    String result = new String(decodedBytes);
    if (log.isDebugEnabled()) {
        log.debug("Decoded string to: " + result);
    }
    return result;
}

private String padString(String value) {
    int mod = value.length() % 4;
    if (mod <= 0) {
        return value;
    }
    int numEqs = 4 - mod;
    if (log.isDebugEnabled()) {
        log.debug("Padding value with " + numEqs + " = signs");
    }
    for (int i = 0; i < numEqs; i++) {
        value += "=";
    }
    return value;
}
}

在 JavaScript 端,您只需要确保您使用了 base64对值进行编码:

var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + encodedValue + 
                  "; expires=" + this.expires.toGMTString() + 
                  "; path=" + this.path;

I have found two solutions to this. Here is the first one.

Add back in padding to Base64 encoded strings. Inspiration for this came from http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/

In this solution, the JavaScript stays the same (base64 encode everything) and the server side looks like:

public class CookieDecoder {

private static final Log log = LogFactory.getLog(CookieDecoder.class);

/**
 * @param cookieValue The value of the cookie to decode
 * @return Returns the decoded string
 */
public String decode(String cookieValue) {
    if (cookieValue == null || "".equals(cookieValue)) {
        return null;
    }
    if (!cookieValue.endsWith("=")) {
        cookieValue = padString(cookieValue);
    }
    if (log.isDebugEnabled()) {
        log.debug("Decoding string: " + cookieValue);
    }
    Base64 base64 = new Base64();
    byte[] encodedBytes = cookieValue.getBytes();
    byte[] decodedBytes = base64.decode(encodedBytes);
    String result = new String(decodedBytes);
    if (log.isDebugEnabled()) {
        log.debug("Decoded string to: " + result);
    }
    return result;
}

private String padString(String value) {
    int mod = value.length() % 4;
    if (mod <= 0) {
        return value;
    }
    int numEqs = 4 - mod;
    if (log.isDebugEnabled()) {
        log.debug("Padding value with " + numEqs + " = signs");
    }
    for (int i = 0; i < numEqs; i++) {
        value += "=";
    }
    return value;
}
}

On the JavaScript side, you just need to make sure you base64 encode the values:

var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + encodedValue + 
                  "; expires=" + this.expires.toGMTString() + 
                  "; path=" + this.path;
夏日落 2024-07-15 16:37:32

第二种解决方案只是对 Base64 编码的字符串进行 URLEncode。 我在这里使用通用编解码器进行编码。 Java 代码:

public class CookieDecoder {

    private static final Log log = LogFactory.getLog(CookieDecoder.class);

    /**
     * @param cookieValue The value of the cookie to decode
     * @return Returns the decoded string
     */
    public String decode(String cookieValue) {
        if (cookieValue == null || "".equals(cookieValue)) {
            return null;
        }
        if (log.isDebugEnabled()) {
            log.debug("Decoding string: " + cookieValue);
        }
        URLCodec urlCodec = new URLCodec();
        String b64Str;
        try {
            b64Str = urlCodec.decode(cookieValue);
        }
        catch (DecoderException e) {
            log.error("Error decoding string: " + cookieValue);
            return null;
        }
        Base64 base64 = new Base64();
        byte[] encodedBytes = b64Str.getBytes();
        byte[] decodedBytes = base64.decode(encodedBytes);
        String result = new String(decodedBytes);
        if (log.isDebugEnabled()) {
            log.debug("Decoded string to: " + result);
        }
        return result;
    }
}

但现在我也必须在 JavaScript 端对其进行解码......
编码:

var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + escape(encodedValue) + 
                  "; expires=" + this.expires.toGMTString() + 
                  "; path=" + this.path;

解码:

var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') {
        c = c.substring(1,c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
        var encodedValue = c.substring(nameEQ.length,c.length);
        return this.base64.decode(unescape(encodedValue));
    }
}
return null;

The second solution is just to URLEncode the Base64 encoded string. I'm using commons codec to do the encoding here. Java Code:

public class CookieDecoder {

    private static final Log log = LogFactory.getLog(CookieDecoder.class);

    /**
     * @param cookieValue The value of the cookie to decode
     * @return Returns the decoded string
     */
    public String decode(String cookieValue) {
        if (cookieValue == null || "".equals(cookieValue)) {
            return null;
        }
        if (log.isDebugEnabled()) {
            log.debug("Decoding string: " + cookieValue);
        }
        URLCodec urlCodec = new URLCodec();
        String b64Str;
        try {
            b64Str = urlCodec.decode(cookieValue);
        }
        catch (DecoderException e) {
            log.error("Error decoding string: " + cookieValue);
            return null;
        }
        Base64 base64 = new Base64();
        byte[] encodedBytes = b64Str.getBytes();
        byte[] decodedBytes = base64.decode(encodedBytes);
        String result = new String(decodedBytes);
        if (log.isDebugEnabled()) {
            log.debug("Decoded string to: " + result);
        }
        return result;
    }
}

But now I have to decode it on the JavaScript side as well...
Encode:

var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + escape(encodedValue) + 
                  "; expires=" + this.expires.toGMTString() + 
                  "; path=" + this.path;

Decode:

var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') {
        c = c.substring(1,c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
        var encodedValue = c.substring(nameEQ.length,c.length);
        return this.base64.decode(unescape(encodedValue));
    }
}
return null;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文