Cookie保存中文 编码

@RequestMapping("/test4")
public void test4(@RequestParam("name") String username,HttpServletResponse response) throws Exception{//保存Cookie
    //首先将浏览器传下来的数据转换成中文(还原)。 
    username = new String(username.getBytes("iso-8859-1"), "utf-8");
    //然后统一以utf-8进行编码, 取时也用utf-8来解码
    username = URLEncoder.encode(username,"utf-8");
    System.out.println(username);
    response.addCookie(new Cookie("username",username));
}
@RequestMapping("/test4-1")
public void test4(HttpServletRequest request) throws Exception{//取出Cookie
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        System.out.println("解码前: key:"+cookie.getName()+"---->"+cookie.getValue());
        //以utf-8来解码
        String decode = URLDecoder.decode(cookie.getValue(),"utf-8");
        System.out.println("解码后: key:"+cookie.getName()+"---->"+decode);
    }
}


你可能感兴趣的:(j2EE)