java中Cookie使用问题(message:invalid character [32] was present in the Cookie value)

1、 问题描述

Servlet中执行下面一段代码:

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
System.out.println( new Date().toString()); Cookie cookie = new Cookie("lasttime", new Date().toString());
response.addCookie(cookie); String s = "欢迎您首次访问该网站!~";
Cookie[] cookies = request.getCookies();
if (cookies != null)
for (Cookie cs : cookies) {
if (cs.getName().equals("lasttime")) {
s = "您上次登录的时间为:" + cs.getValue().replace("-", " ");
}
} response.getWriter().print(s);
}

抛出如下异常:

java中Cookie使用问题(message:invalid character [32] was present in the Cookie value)

2、 追根溯源

出现上述问题觉得很奇怪,因为程序编译通过,至少证明没有语法错误,根据编译器提示,定位问题到:

Cookie cookie = new Cookie("lasttime",  new Date().toString());
response.addCookie(cookie);

查看JAVAEE-API,发现有如下

java中Cookie使用问题(message:invalid character [32] was present in the Cookie value)

回过去看代码,发现

输入:

System.out.println( new Date().toString());
输出:

Fri Apr 20 21:56:39 CST 2018

很明显输出字符串中存在 空格 ,所以程序会报错,存在无效字符。

3、解决方案

解决问题的方法其实很简单,只要字符串中不存在空格即可成功,下面将给出几种具体的解决办法,程序修改如下:

法一

思路:用“-”代替“ ”,之后记得换回来即可,程序成功运行。

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
System.out.println( new Date().toString()); Cookie cookie = new Cookie("lasttime", new Date().toString().replace(" ", "-"));
cookie.setMaxAge(60*60);
response.addCookie(cookie); String s = "欢迎您首次访问该网站!~";
Cookie[] cookies = request.getCookies();
if (cookies != null)
for (Cookie cs : cookies) {
if (cs.getName().equals("lasttime")) {
s = "您上次登录的时间为:" + cs.getValue().replace("-", " ");
}
} response.getWriter().print(s);
}

法二

思路:进行URL编码,然后把编码后的字符串放到Cookie中,之后进行URL解码即可。

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
System.out.println( new Date().toString()); Cookie cookie = new Cookie("lasttime", URLEncoder.encode(new Date().toString(), "UTF-8"));
cookie.setMaxAge(*);
response.addCookie(cookie); String s = "欢迎您首次访问该网站!~";
Cookie[] cookies = request.getCookies();
if (cookies != null)
for (Cookie cs : cookies) {
if (cs.getName().equals("lasttime")) {
s = "您上次登录的时间为:" + URLDecoder.decode(cs.getValue(), "UTF-8");
}
}
response.getWriter().print(s);
}

程序运行正常,符合预期值。

上一篇:我的数据,我做主——RecoveryManager Plus


下一篇:用yii2给app写接口(下)