cookie保存中文时出现如下异常:
Control character in cookie value, consider BASE64 encoding your value
很明显是编码问题,解决办法:在保存cookie之前进行转码。
// 添加一个cookie
public static boolean addCookie(String str, HttpServletResponse response) {
String name = null;
try {
name = URLEncoder.encode(str, "utf-8"); // 转码
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Cookie cookie = new Cookie("user", name);
cookie.setMaxAge(60 * 60 * 24 * 14);// cookie保存两周
response.addCookie(cookie);
System.out.println("添加cookie成功");
return true;
}
// 得到cookie
public static String getCookie(HttpServletRequest request) {
String name;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println("cookie: " + cookie.getName());
if ("user".equals(cookie.getName())) {
name = cookie.getValue();
return name;
}
}
}
return null;
}