2008-11-07 5 views
2

로그인 양식 (username == email address)를 미리 채울 수 있도록 내 응용 프로그램이 사용자 전자 메일 주소를 쿠키에 저장해야합니다. 자바 스크립트에서 쿠키 값을 설정했습니다. JavaScript에서 읽으면 [email protected]이됩니다. 파이어 폭스의 쿠키 뷰어에서 보면 [email protected]이 나온다.자바의 쿠키에서 이메일 문자열 읽기

그러나 자바에서 서버 측에서 읽으려고하면 foo 만 얻습니다.

여기에 일종의 인코딩/디코딩이 필요합니까? 그렇다면 JavaScript와 Java 모두에서 디코딩 할 수있는 방법으로 어떻게해야합니까?

미리 감사드립니다! - 마이클

답변

0

당신은 쿠키의 값 부분을 탈출해야합니다. setValue의 (문자열)에 대한 javax.servlet.http.Cookie DOCO에서

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

:

쿠키가 생성 후에, 쿠키에 새로운 값을 할당합니다. 당신이 이진 값을 사용하는 경우 BASE64 인코딩을 사용할 수 있습니다. 버전 0 쿠키

, 값은 표지판, 콜론, 세미콜론에서 표지판, 쉼표, 따옴표, 슬래시, 물음표, 동일, 공백, 괄호, 괄호를 포함 할 수 없습니다. 빈 값 은 모든 브라우저에서 같은 방식으로 작동하지 않을 수 있습니다. 난 당신이 BASE64 필요 같은데요

내가이 두 가지 솔루션을 발견

+0

참조하시기 바랍니다 포스트 기호...(댓글에 300 자 제한이 있습니까?) – bowmanmc

0

(자바를 통해) 밖으로 방법 (자바 스크립트를 통해)의 방법과 그것을 인코딩. 여기가 첫 번째 것입니다.

는 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; 
} 
} 

: 이것에 대한 영감은, 자바 스크립트 같은 (base64로 모든 것을 인코딩) 유지와 같은 서버 측 보이는이 솔루션에서 http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/

에서 온 base64는 다음 값을 인코딩합니다.

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

두 번째 해결책은 Base64로 인코딩 된 문자열을 URL 인코딩하는 것입니다. 나는 코 몬즈 코덱을 사용하여 여기 엔코딩을하고있다. 자바 코드 :

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

하지만 지금뿐만 아니라 자바 스크립트 측에서 그것을 해독해야 ... 인코딩 :

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;