关于cookie中文乱码问题

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);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当在C#中读取cookie中的中文时,可能会遇到乱码问题。这是因为默认情况下,读取cookie时会使用UrlDecode方法对存储在cookie中的中文进行解码,而这可能会导致乱码。解决这个问题的方法是使用其他方法来解码cookie中的中文。一个常见的方法是使用Unicode编码来对中文进行编码和解码,这样可以确保中文字符在cookie中的正确显示。另外,还可以在写入cookie时使用特定的编码方式来确保中文字符的正确保存。如果在读取cookie时仍然遇到乱码问题,可以通过在断点处查看读取到的字符串来进一步分析问题的原因。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [ie获取cookie数据,中文乱码cookie中文乱码终极解决办法](https://blog.csdn.net/cplvfx/article/details/129008933)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [解决cookie储存中文乱码](https://blog.csdn.net/weixin_44542088/article/details/91348442)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值