关于cookie中文乱码问题

本文介绍了如何处理Cookie存储中文字符时出现的乱码问题。通过使用URLEncoder对中文进行编码,并在读取时使用URLDecoder解码,确保了中文字符在Cookie中的正确存储与读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值