以前用cookie只是存一些简单的英文串或者其他的登录信息,没有涉及到中文,所以对cookie也没多作研究,最近一项目中需要用到cookie,并且要用cookie存储中文信息,不料却出现差错,存进去了,发现数据库表里全是乱码,而且对cookie串拆分,读出来的发现并不是自己想要的结果。后来发现存储中文需要有一个编码,读出来的时候以同样的编码方式解码。
中文与英文字符不同,中文属于Unicode字符,在内存中占4个字符,而英文属于ASCII字符,内存中只占2个字节。Cookie中使用Unicode字符时需要对 Unicode字符进行编码,否则会乱码。编码可以使用java.net.URLEncoder类的encode(String str, String encoding)方法,解码使用java.net.URLDecoder类的decode(String str, String encoding)方法,例如:
// 使用中文的 Cookie. name 与 value 都使用 UTF-8 编码
Cookie cookie = new Cookie(
URLEncoder.encode("姓名", "UTF-8"),
URLEncoder.encode("老王", "UTF-8"));
response.addCookie(cookie); // 发送到客户端
读取时候:
if(request.getCookies() != null){
for(Cookie cc : request.getCookies()){ // 遍历所有的Cookie
String cookieName = URLDecoder.decode(cc.getName(), "UTF-8");
String cookieValue = URLDecoder.decode(cc.getValue(), "UTF-8");
out.println(cookieName + "=" + cookieValue + "; <br/>");
}
}
%提示:Cookie中保存中文只能编码。一般使用UTF-8编码即可。不推荐使用GBK等中文编码,因为浏览器不一定支持,而且JavaScript也不支持GBK编码。
Cookie不仅可以使用ASCII字符与Unicode字符,还可以使用二进制数据。例如在Cookie中使用数字证书,提供安全度。使用二进制数据时也需要进行编码。下面的例子使用BASE64编码在Cookie中保存二进制文件:
File file = new File(this.getServletContext().getRealPath("cookie.
gif"));
byte[] binary = new byte[(int)file.length()]; // 二进制数组
// 从图片文件读取二进制数据.
InputStream ins = this.getServletContext().getResourceAsStream
(file.getName());
ins.read(binary);
ins.close();
String content = BASE64Encoder.class.newInstance().encode(binary);
// BASE64 编码
Cookie cookie = new Cookie("file", content);
// 包含二进制数据的 Cookie
response.addCookie(cookie); // 将 Cookie 发送到客户端
从 Cookie 中获取到的二进制图片:<img src="base64_decode.jsp" /> <br/>
<textarea id='cookieArea' style='width:100%; height:200px; '></textarea>
<script type="text/javascript">cookieArea.value=document.cookie;</script>
程序使用的二进制数据来自根目录下的cookie.gif文件。程序先将二进制数据写进客户端Cookie中,然后又将Cookie中的二进制数据还原并显示。输入框中用JavaScript程序显示了客户端Cookie的所有内容。
解码并显示图片的源代码如下:
out.clear(); // 清除输出
for(Cookie cookie : request.getCookies()){ // 遍历Cookie
if(cookie.getName().equals("file")){ // 找到名为file的Cookie
byte[] binary =
BASE64Decoder.class.newInstance().decodeBuffer(cookie.
getValue().replace(" ", "")); // 解码BASE64编码的二进制内容
response.setHeader("Content-Type", "image/gif");
// 设置内容类型为 gif 图片
response.setHeader("Content-Disposition", "inline;
filename=cookie.gif");
[color=blue][/color][size=x-small][/size]
response.setHeader("Connection", "close");
response.setContentLength(binary.length); // 设置输出内容的长度
response.getOutputStream().write(binary); // 输出到客户端
response.getOutputStream().flush(); // 清空缓存
response.getOutputStream().close(); // 关闭输出流
return;
}
}
%注意:本程序仅用于展示Cookie中可以存储二进制内容,并不实用。由于浏览器每次请求服务器都会携带Cookie,因此Cookie内容不宜过多,否则影响速度。Cookie的内容应该少而精。
Cookie中保存中文乱码 解决办法
最新推荐文章于 2024-02-20 17:35:58 发布