用cookie来存贮中文要进行编码与解码 否则会出现乱码的情况(tomcat7会乱码 tomcat8好像不会)
下面展示代码 (加粗代码是 关键 其实就是编码一下和解码一下而已)
1.添加含中文的cookie示例
String name = request.getParameter("name");
name = java.net.URLEncoder.encode(name,"gbk");
javax.servlet.http.Cookie c = new javax.servlet.http.Cookie("name",name);
c.setMaxAge(10000);
response.addCookie(c);
2.取出含中文cookie示例
从cookie中取含有中文的数据时:
javax.servlet.http.Cookie cs[] = request.getCookies();
for(javax.servlet.http.Cookie c:cs){
if(c.getName().equals("name")){
String cval = c.getValue();
cval = URLDecoder.decode(cval,"gbk");
out.println("name = " + cval);
}
}