調用Cookie對象的構造函數可以創建Cookie。Cookie對象的構造函數有兩個字符串參數:Cookie名字和Cookie值。

Cookie cookie = new Cookie(name,value);

調用下面的方法時出現一個問題
response.addCookie(cookie);//cookie 是一個Cookie實例

問題報錯:java.lang.IllegalArgumentException: Control character in cookie value, consider BASE64 encoding your value

很顯然Cookie之中存在了非法參數,經過測試發現cookie之中包含""r"n"、""n"時就會出現這個異常。

因為cookie中部分值是通過文本框錄入的,在<textarea/>標簽中鍵入回車鍵后,value值中就加入了""r"n",
把這樣的值賦給cookie,執行response.addCookie(cookie);時則出現異常。

解決辦法:使用String類的replace()方法。
Java代碼

1 str = str.replace(""r"n", "<br>");            
2 str = str.replace(""n", "<br>");
3 
4 Cookie cookie = new Cookie('cookName',str);
5 //永久有效
6 cookie.setMaxAge(60*60*24*365);
7 response.addCookie(cookie);

剛才看到Base64錯誤,通常不將數據直接保存在cookie中,而要進行Base64編碼

String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes("UTF-8"))); //設置UTF-8否則會亂碼
Debug.log("Ba64:"+ cookieValueBase64, module);
cookieValueBase64 
= cookieValueBase64.replace(""r"n""");              
cookieValueBase64 
= cookieValueBase64.replace(""n""");
Cookie cookie = new Cookie(key, cookieValueBase64);
cookie.setMaxAge(time);
cookie.setPath(
"/");// 設置適用路經
res.addCookie(cookie);// 將cookie添加到response對象中。由response對象返回給戶端  


取得時候:new String(Base64.decode(ck.getValue()),"UTF-8");       

這樣做就行了嗎?發現還是不夠,出現什么問題呢?
原來如果cookie值中出現等號,那么取出來的值只取等號前面的值,等號及等號后面的值會被忽略

Base64編碼難保不出現等號,怎么解決呢?采用UrlEncoder和UrlDecoder,存的時候:

String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes("UTF-8")));
cookieValueBase64 
= cookieValueBase64.replace(""r"n""");              
cookieValueBase64 
= cookieValueBase64.replace(""n""");     
String cookieValueUrlEncode = URLEncoder.encode(cookieValueBase64, "UTF-8");

取的時候:

new String(Base64.decode(URLDecoder.decode(ck.getValue(), "UTF-8")),"UTF-8");

這樣很多特殊字符就可以了。