在javaweb中使用Cookie经常会出现乱码问题。

解决方法:对中文进行编码和解码

存储到Cookie中时:

String str = URLEncoder.encode("你好","UTF-8");
  Cookie cookie = new Cookie("aaa", str);
  cookie.setMaxAge(600);
  response.addCookie(cookie);
  response.sendRedirect("index.jsp");

从Cookie中获取时:

Cookie[] cookies = request.getCookies();
     for(Cookie c : cookies){
      if(c.getName().equals("aaa")){
       String result = URLDecoder.decode(c.getValue(),"UTF-8");
       out.println(result);
      }  
     }

posted on 2013-06-10 21:08  aparche  阅读(1595)  评论(0编辑  收藏  举报