当前位置: 代码迷 >> J2EE >> servlet获取cookies - cookies中文乱码解决思路
  详细解决方案

servlet获取cookies - cookies中文乱码解决思路

热度:110   发布时间:2016-04-22 00:40:53.0
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 (UnsupportedEncodingException 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;
}
  相关解决方案