对cookie进行编码
String departmentName ="浙江省杭州市滨江区";
// 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码
CookiesUtil.setCookie(response, CommonUtils.DEPARTMENTNAME, URLEncoder.encode(departmentName,"utf-8"),60);
对cookie进行解码
Cookie[] ck = request.getCookies();//获取cookie
for (Cookie c : ck) {
String value=c.getValue();//获取cookie中的值
/*URLDecoder.decode(value,"utf-8"):保存在cookie中的汉字进行转码,
* 如果不转码,打印出来照样会乱码。
* 注意:编码时采用的是URLEncoder,转码是URLDecoder
* */
value=URLDecoder.decode(value,"utf-8");
System.out.println(value);
}
工具类
public class CookiesUtil {
public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int... time) {
// new一个Cookie对象,键值对为参数
Cookie cookie = new Cookie(name, value);
// tomcat下多应用共享
cookie.setPath("/");
if (time.length != 0) cookie.setMaxAge(time[0]);
// 将Cookie添加到Response中,使之生效
response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie
return response;
}
}