在学习cookie获取时间信息的过程中突然报错
我的代码如下:
//1.获取当前的日期
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String format = simpleDateFormat.format(date);
//2.把日期写到cookie
Cookie cookie = new Cookie("dateTime", format);
//3.响应给浏览器
response.addCookie(cookie);
错误信息:
Servlet.service() for servlet [com.servlet.cookie.dateServlet] in context with path [/Servlet_Learnning_8] threw exception
java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value
经过百度翻译出来的意思是
路径为[/servlet learning[/servlet learning]的上下文中servlet[com.servlet.cookie.dateservlet]的servlet.service()引发异常
java.lang.illegalargumentException:cookie值中存在无效字符[32]
发现在tomcat8之后addCookie不能有空格,在ASCII码中,32对应的字符是空格
解决方法如下:
方法一:把空格删除或者修改为其他的字符,例如 "-","/" 等等。
方法二:把有空格的字符进行编码,修改的正确代码如下:
//1.获取当前的日期
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String format = simpleDateFormat.format(date);
//把format进行字符编码
String encode = URLEncoder.encode(format,"utf-8");
//2.把日期写到cookie
Cookie cookie = new Cookie("dateTime", encode);
//3.响应给浏览器
response.addCookie(cookie);
String dateTime = null;
//4.获取cookie
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for (Cookie cookie2 : cookies) {
if(cookie2.getName().equals("dateTime")) {
//上面得到的日期的经过编码的,则要对得到的值进行解码
dateTime = java.net.URLDecoder.decode(cookie2.getValue(), "utf-8");
}
}
}
response.setContentType("text/html;charset=utf-8");
if(dateTime != null) {
response.getWriter().write("上次的登录时间为:" + dateTime);
}else {
response.getWriter().write("你是第一次登录");
}
结果为: