创建Cookie对象遇到的问题:
1.创建Cookie对象语句,并添加到response中
Cookie c = new Cookie(String name,String value);
response.addCookie(c);
运行时候遇到问题:
java.lang.IllegalArgumentException: Control character in cookie value or attribute.
解决办法:在创建Cookie对象时候指定编码
URLEncoder.encode(value, "UTF-8")
Cookie c = new Cookie(name,URLEncoder.encode(value,"UTF-8"));
2.在获取Cookie对象中的name和value的时候
Cookie[] cs = request.getCookies();
URLDecoder.decode(getName(), "utf-8");
URLDecoder.decode(c.getValue(), "utf-8");
本文介绍了在Java Web开发中创建Cookie对象时遇到的字符编码问题及解决方案。当Cookie值包含特殊字符时,直接创建Cookie可能导致异常。文章提供了解决方案,即使用URLEncoder.encode进行编码,并展示了如何在读取Cookie时进行解码。
351

被折叠的 条评论
为什么被折叠?



