在开发过程中,我采用 Cookie 存储了一些中文字符,但是读取的时候老是为空,最后感觉是编码问题,就自己手动搜了下,最后解决了,在这里分享给大家。
存储时候进行转码
//对含有中文字符的Cookie进行转码
String data = java.net.URLEncoder.encode(request.getParameter("data"),"UTF-8");
//存储Cookie
Cookie cookie = new Cookie(request.getParameter("currentTime"), data );
//设置Cookie存活时间
cookie.setMaxAge(5);
//将Cookie添加到本地
ServletActionContext.getResponse().addCookie(cookie);
请注意:一定要采用 UTF-8,本人采用 GBK 依然存在问题
读取的时候进行解码
//获取 request 对象
request = ServletActionContext.getRequest();
// 获取 Cookie 数组
Cookie[] cookies = request.getCookies();
String param = null;
// 遍历数组,得到数据
for(Cookie cookie : cookies){
if(cookie.getName().equals(request.getParameter("currentTime"))){
param = cookie.getValue();
//进行解码
param = URLDecoder.decode(param, "UTF-8");
}
}
总结:主要就是以下两个步骤:
- 对存入 Cookie 中的数据进行编码
- 从 Cookie 中的数据解码
解决Cookie中中文字符问题
本文介绍了一种解决Cookie中存储中文字符时出现乱码的方法。通过使用URLEncoder.encode进行编码,并确保使用UTF-8编码格式,有效地解决了读取时显示为空的问题。
1489

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



