解决ie下cookie中文乱码问题

今天在项目中碰到一个问题,chrome,Firefox浏览器下cookie中的中文都正常,唯独IE下出现乱码。
项目中全部采用utf-8编码,可是IE下现实仍然不正常。最终进过排查,发现IE传到后台的cookie值 ,
仍然采用ISO8859-1编码格式,所以导致了以utf-8解析的时候出现错误的情况。

![例如,这是IE浏览时cookie值:ÐìÖÝ (徐州的乱码形式)]
https://img-blog.csdn.net/20160315132528611
[这是chrome浏览时cookie值:å¾å· (徐州的乱码形式)]
(https://img-blog.csdn.net/20160315132909551)

这时候,对chrome和IE进行不同的解码就可以。
IE下:cookValue=new String(cookie.getValue().getBytes(“ISO8859-1”)); //这里结果直接得到中文
chrome下:cookValue=cookie.getValue();

代码如下:
Cookie cookie = (Cookie) cookieMap.get(name);
String cookValue = null;

if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
    // IE8,9浏览器
    cookValue=new String(cookie.getValue().getBytes("ISO8859-1"));
    return cookValue;
}else if (request.getHeader("User-Agent").toUpperCase().indexOf("TRIDENT") > 0) {
    // IE11浏览器
    cookValue=new String(cookie.getValue().getBytes("ISO8859-1"));
    return cookValue;
} else  {
    // 其他浏览器
    cookValue=cookie.getValue();
}

cookValue = java.net.URLDecoder.decode(cookValue, "utf-8");
return utf8Togb2312(cookValue);//utf8Togb2312()是utf-8转中文函数,可以百度一个

你可能感兴趣的:(java-web技术)