读cookie中文字符乱码问题

写cookie

  Cookie cookie = new Cookie("username", java.net.URLEncoder.encode(username,"UTF-8"));
   cookie.setMaxAge(50*60);//不设置的话,则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位   
   response.addCookie(cookie);

读cookie

 

Cookie cookies[] = request.getCookies();   
 if (cookies != null)   
 {   
     for (int i = 0; i < cookies.length; i++)   
     {   
       
         if (cookies[i].getName().equals("username")) 
          
         {  
          username=java.net.URLDecoder.decode(cookies[i].getValue().trim(),"UTF-8");
         }   
     }   
 } 

 

总结:在保存到cookie的时候要用URLEncoder.encode(username,"UTF-8"))方法保存

读的时候要用URLDecoder.decode(cookies[i].getValue().trim(),"UTF-8")方法来解码

posted @ 2012-12-17 13:09  残剑_  阅读(413)  评论(0编辑  收藏  举报