cookie的特殊字符的编码和解码来解决乱码问题;
编码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
String str="hello world";
String str1 = URLEncoder.encode(str, "utf-8");// 把str 编码为str1
Cookie cookie = new Cookie("str1", str1); //保存在cookie响应给浏览器
response.addCookie(cookie); //在另一个servlet中解码
}
解码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("str1")) { //找到 str1 的cookie
String decode = URLDecoder.decode(cookie.getValue(), "utf-8");
System.out.println(decode);
response.getWriter().print(decode); //显示在页面
}
}
}
首先访问编码,然后访问解码,结果在浏览器中显示;