标题重复率过高,只能改为HTTP Status 500,java学习第n天
Message An invalid character [32] was present in the Cookie value
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value
org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateCookieValue(Rfc6265CookieProcessor.java:182)
org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:115)
org.apache.catalina.connector.Response.generateCookieString(Response.java:974)
org.apache.catalina.connector.Response.addCookie(Response.java:926)
org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:385)
com.wuyue.cookie.Cookietest.doPost(Cookietest.java:67)
com.wuyue.cookie.Cookietest.doGet(Cookietest.java:75)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/9.0.6
查询ASCCII表可知,[32]代表一个空格
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); cookie.setValue(str_date); //设置cookie的存活时间 cookie.setMaxAge(60*60);//1小时 这里是按照秒来及时的 //再次发送cookie response.addCookie(cookie); //获取cookie的value值 String value = cookie.getValue(); response.getWriter().write("<h1>欢迎回来,您上次访问时间为"+value+"<h1>");
);
第一行代码时间格式日和HH之间有一个空格。cookie在tomcat8之后虽然可以支持中文,但还是不支持特殊字符,这里如果要保留空格的话,必须要用URL编码如下所示:
Date date = new Date();
//cookie在tomcat8之后虽然可以支持中文,但还是不支持特殊字符,这里如果要保留空格的话,必须要用URL编码
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");//时间格式日和HH之间有一个空格
String str_date = sdf.format(date);
System.out.println("编码前:"+str_date);//编码前:2020年12月08日 16:39:46
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后:"+str_date);//编码后:2020%E5%B9%B412%E6%9C%8808%E6%97%A5+16%3A39%3A46
cookie.setValue(str_date);
//设置cookie的存活时间
cookie.setMaxAge(60*60);//1小时 这里是按照秒来及时的
//再次发送cookie
response.addCookie(cookie);
//获取cookie的value值
String value = cookie.getValue();
System.out.println("解码前:"+value);
//URL解码
value = URLDecoder.decode(value, "utf-8");
System.out.println("解码后:"+value);
response.getWriter().write("<h1>欢迎回来,您上次访问时间为"+value+"<h1>");
当然新建cookie时也要url编码
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
System.out.println("编码前:"+str_date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
System.out.println("编码后:"+str_date);
Cookie lastTime = new Cookie("lastTime", str_date);
//设置cookie的存活时间
lastTime.setMaxAge(60*60);//1小时 这里是按照秒来及时的
//发送cookie
response.addCookie(lastTime);