要想在cookie中存储中文,那么必须使用URLEncoder类里面的encode(String s, String enc)方法进行中文转码,例如:
Cookie cookie = new Cookie("userName", URLEncoder.encode("Hello你好", "UTF-8"));
response.addCookie(cookie);
在获取cookie中的中文数据时,再使用URLDecoder类里面的decode(String s, String enc)进行解码,例如:
URLDecoder.decode(cookies[i].getValue(), "UTF-8")
主要代码:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置服务器端以UTF-8编码进行输出
response.setCharacterEncoding("UTF-8");
//设置浏览器以UTF-8编码进行接收,解决中文乱码问题
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
//获取浏览器访问访问服务器时传递过来的cookie数组
Cookie[] cookies = request.getCookies();
//如果用户是第一次访问,那么得到的cookies将是null
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookies[i].getName().equals("userName")) {
//
out.write(URLDecoder.decode(cookies[i].getValue(), "UTF-8"));
}
}
} else {
out.write("it's your first access.");
}
//用户访问过之后重新设置用户的访问时间,存储到cookie中,然后发送到客户端浏览器
Cookie cookie = new Cookie("userName", URLEncoder.encode("NIHAO你好~", "UTF-8"));
//将cookie对象添加到response对象中,这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
response.addCookie(cookie);
}