cookie实例---显示上一次访问的时间与java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value

2019-08-09 00:00:00 实例 cookie

创建Cookie,名为lasttime,值为当前时间,添加到response中;

A.jsp中获取请求中名为lasttimeCookie

如果不存在输出“您是第一次访问本站”,如果存在输出“您上一次访问本站的时间是xxx”

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ page import="java.util.Date" %>
 4 <%@ page import="java.text.SimpleDateFormat" %>
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <title>Insert title here</title>
10 </head>
11 <body> 
12     <%
13         Date date = new Date();
14         SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
15         String time = sdf.format(date);
16         Cookie c = new Cookie("lasttime",time);
17         response.addCookie(c);
18         Cookie cs[] = request.getCookies();
19         boolean tag = false;
20         if(cs != null && cs.length > 0){
21             for(Cookie ck : cs){
22                 if(ck.getName().equals("lasttime")){
23                     tag = true;
24                     out.write("您上一次的访问时间为:" + ck.getValue());
25                     break;
26                 }
27             }
28         }
29         if(!tag){
30             out.write("这是您第一次访问本网站");
31         }
32     %>
33 </body>
34 </html>

练习时出现了错误java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value

原因是设置时间格式化时使用了yyyy-MM-dd HH:mm:ss这样的格式,前端和后段之间出现了空格,也就是错误中提到的character [32],而cookie中不能出现空格,更改即可。

相关文章