在Tomcat8.0中,遇到了Cookie中value值中文乱码的问题
写了一个通用的方法,用于查询value值为中文,指定key值的cookie
public static Cookie add(String name,String value) {
try {
if(name==null||value==null){
return null;
}else {
//利用base64编码
BASE64Encoder base64Encoder=new BASE64Encoder();
String encode = base64Encoder.encode(value.getBytes("UTF-8"));
Cookie cookie =new Cookie(name,encode);
return cookie;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static Cookie getChineseCookie(String name,Cookie[] cookies) {
try {
if (name==null || cookies==null || cookies.length==0){
return null;
}else {
for (Cookie cookie:cookies){
if(name.equals(cookie.getName())){
//利用了BASE64解码
BASE64Decoder base64Decoder=new BASE64Decoder();
byte[] bytes = base64Decoder.decodeBuffer(cookie.getValue());
String value =new String(bytes,"UTF-8");
Cookie cookie1 =new Cookie(cookie.getName(),value);
return cookie1;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
本文介绍了在Tomcat 8.0环境中处理Cookie中文乱码问题的详细过程,通过Base64编码和解码操作,展示了如何正确设置和获取包含中文的Cookie值。
1195

被折叠的 条评论
为什么被折叠?



