URLEncode解决Cookie存取中文乱码

中文属于Unicode编码,

而英文属于Ascll编码,

Cookie中又只能存储英文,要想向cookie中存取中文就要对中文进行编码

当向cookie中存储时,使用URLEncode类中的encode方法对文本进行转码

当从cookie中读取时,使用URLDecode类中的decode方法进行解码

实例如下:

String username = request.getParameter("username");	//假设获取到的值为中文
username = URLEncode.encode(username);	//使用encode方法对字符串进行转码
Cookie cookie = new Cookie("username",username);
response.addCookie(cookie);	//	保存到cookie中

Cookie[] cookie = request.getCookie();
for(Cookie cok:cookie){
	if(cok.getName().equals("username")){
		String name = cok.getValue();
		name = URLDecode.decode(name,"utf-8");	//到此为止完成解码,name此时为中文显示
	}

}	


你可能感兴趣的:(Java,JSP)