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的编码,难怪总是出现错误或者乱码,知道问题的所在就好解决拉,转换一下编码试试:
//一个有中文内容的CookieString 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