中文乱码
学习Cookie时遇到的乱码问题
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Cookie[] cookies = req.getCookies();
PrintWriter out = resp.getWriter();
if(cookies != null){
out.print("上次访问本站的用户是:");
for (int i = 0; i<cookies.length; i++){
Cookie cookie = cookies[i];
if(cookie.getName().equals("name")){
out.print(cookie.getValue());
}
}
}else{
out.print("这是第一次访问本站");
}
Cookie cookie = new Cookie("name","呆瓜");
cookie.setMaxAge(24*60*60);//有效期 24小时
resp.addCookie(cookie);
}
产生问题-中文乱码
尝试解决
添加 Header
resp.setHeader("Content-Type","text/html;charset=utf-8");
成功实现中文乱码
扩展
不过一般也有另一种思路(利用URLEncoder进行编码 解码 操作)
URLEncoder.encode("","UTF-8") //编码
URLDecoder.decode("","UTF-8"); //解码
这也比较安全 也不会出现乱七八糟的问题出来