Jsp中存取Cookie的“中文”问题解决方法

Cookie是个好东西,我们时常会利用它来为我们的程序提供一些方便。可是Jsp中却存在不能使用中文Cookie名的问题,一旦使用了中文的名字程序就会报错,内容则会成为乱码,问题已经出现了,原因呢?

先看一下API:(注意红色部分)

public Cookie(java.lang.String name, java.lang.String value)Constructs a cookie with a specified name and value.
The name must conform to RFC 2109. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begin with a $ character. The cookie's name cannot be changed after creation.

The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie's value can be changed after creation with the setValue method.

By default, cookies are created according to the Netscape cookie specification. The version can be changed with the setVersion method.

哈哈~~~根据RFC 2109中的规定,在Cookie中只能包含ASCII的编码,难怪总是出现错误或者乱码,知道问题的所在就好解决拉,转换一下编码试试:

//一个有中文内容的Cookie
String str = "我们都有一个家,名字叫中国!";
Cookie cookie = new Cookie("name", URLEncoder.encode(str, "UTF-8"));
response.addCookie(cookie);

//取出Cookie中的中文内容
Cookie [] cookies = request.getCookies();
String str = "";
for(int i=0;i<cookies.length;i++){ 
    if(cookies[i].getName().equals("name")) {
        str = cookies[i].getValue();
    }
}
out.println(URLDecoder.decode(str, "UTF-8"));

朋友们可以再起个中文名字试试 :)

author 五斗米 <如转载请保留作者和出处>
blog http://blog.csdn.net/mq612

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值