servlet获取cookies ------- cookies中文乱码
Java code
Cookie[] cookies = request.getCookies();
// System.out.println(cookies.length);
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
// System.out.println(cookies[i].getValue());
if ("username".equals(cookies[i].getName())) {
nameValue = cookies[i].getValue().toString();
System.out.println("储存的cookies是:" + nameValue);
answer = "true";
}
}
数字正常 中文乱码 网上的答案似乎不能解决问题
------解决方案--------------------
public void save(String cookieName, String cookieValue, int maxAge) {
try {
cookieValue = java.net.URLEncoder.encode(cookieValue, "utf-8");
Cookie newCookie = new Cookie(cookieName, cookieValue);
newCookie.setMaxAge(maxAge);
response.addCookie(newCookie);
} catch (Unsupported
EncodingException e) {
e.printStackTrace();
}
}
public String getCookieValue(String cookieName) {
String cookieValue = null;
try {
Cookie[] sysCookies = request.getCookies();
if (sysCookies != null) {
for (int i = 0; i < sysCookies.length; i++) {
if (sysCookies[i].getName().equals(cookieName)) {
cookieValue = sysCookies[i].getValue();
cookieValue = java.net.URLDecoder.decode(cookieValue,
"utf-8");
break;
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return cookieValue;
}