项目当中用到cookie保存中文,但是会报如下错误:
Control character in cookie value, consider BASE64 encoding your value
大概意思是保存到cookie当中的值存在控制字符,无法保存。但实际上数据是不存在这种问题的。再看后面的那句话,好像是将要保存的值进行了base64编码,可能是因为中文在编码时出现乱码导致一些控制字符的出现。
解决方案:将要保存的值进行URLEncoder.encode(value,"utf-8")编码。
在提取时,同样进行解码:
- public static void setCookie(String name, String value, Integer time,HttpServletResponse response) {
- try {
-
- value = URLEncoder.encode(value,"UTF-8");
-
- } catch (UnsupportedEncodingException e) { }
- Cookie cookie = new Cookie(name, value);
- cookie.setPath("/");
- cookie.setMaxAge(time);
- response.addCookie(cookie);
- }
-
-
- public static String getCookie(String name, HttpServletRequest request) {
- Cookie[] cs = request.getCookies();
- String value = "";
- if (cs != null) {
- for (Cookie c : cs) {
- if (name.equals(c.getName())) {
- try {
-
-
- value = URLDecoder.decode(c.getValue(),"UTF-8");
-
- } catch (UnsupportedEncodingException e) {
- }
- return value;
- }
- }
- }
- return value;
-
- }
转自:http://amcucn.javaeye.com/blog/403857
Control character in cookie value, consider BASE64 encoding your value-Cookie保存中文出错[转]
原文:http://www.cnblogs.com/volare/p/3938049.html