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

Reading an email string from a cookie in java

本文关键字:读取 电子邮件 字符串 cookie java 中的      更新时间:2023-09-26

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

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

我需要在这里进行某种编码/解码吗?如果是这样的话,我该如何用JavaScript和Java都可以解码的方式来完成它?

提前感谢!-Michael

从javax.servlet.http.Cookie文档获取setValue(String):

在之后为cookie分配新值创建cookie。如果您使用二进制值,您可能需要使用BASE64编码。

使用版本0Cookie,值不应包含空白、括号、圆括号,等号、逗号、双引号,斜杠、问号、符号处的,冒号和分号。空值可能在所有方面都不一样浏览器。

我猜您需要在输入(通过JavaScript)和输出(通过Java)

时对其进行BASE64编码

您需要转义cookie的值部分。

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

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

向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;

第二个解决方案只是对Base64编码的字符串进行URLEncode。我在这里使用commons编解码器进行编码。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;