关于cookie中文乱码问题

来源:互联网 发布:超人软件站下载 编辑:程序博客网 时间:2024/06/11 23:20

cookie存储中文乱码问题

因为cookie默认是ASCII编码的方式,因此保存cookie时需要将中文转换成ASCII编码。

1. 错误演示

Cookie cookie = new Cookie("username","张三");response.addCookie(cookie);

上面为错误代码,会报java.lang.IllegalArgumentException: Control character in cookie value or attribute异常。

2. 处理方案

对于要存储到cookie的数据先进行URLEncoder编码

String username = URLEncoder.encode("张三","utf-8");Cookie cookie = new Cookie("username",username);response.addCookie(cookie);

在jsp里面,如果要取出cookie的值,有两种方式可以实现

  • Java代码实现
Cookie[] cookies = request.getCookies();String name = null;if(cookies != null){    for(int i = 0; i < cookies.length; i++){        if(cookies[i].getName().equals("username")){            name = cookies[i].getValue();            break;        }    }}
<input type='text' name='username' id='name' /><textarea><%= URLDecoder.decode(name,"utf-8") %></textarea>
  • 另外javascrpipt中提供了decodeURI可以对URLEncode编码的字符进行解码
function fun(){    var name = "${cookie.username.value}";    document.getElementById("name").value = decodeURI(name);}
原创粉丝点击