Servlet之Cookies汉字编码问题

来源:互联网 发布:手机数据流量无法上网 编辑:程序博客网 时间:2024/06/14 22:05

在java中Cookies只能接受ASCII编码,因此如果想要将汉字设置到Cookie中,则需要编码和解码.

JAVA中的java.net.URLEncoder可用来编码;类java.net.URLDecoder可用来解码:

上代码:

添加Cookies:

Cookie cookie1=new Cookie("user",URLEncoder.encode("凯旋","UTF-8"));Cookie cookie2=new Cookie("password", "123456");response.addCookie(cookie1);response.addCookie(cookie2);

读取Cookies代码:

Cookie[] cookies=request.getCookies();for (Cookie cookie : cookies) {System.out.println(cookie.getName()+"---------"+URLDecoder.decode(cookie.getValue(),"UTF-8"));}

打印结果:

user---------凯旋password---------123456


0 0
原创粉丝点击