java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value

在学习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("你是第一次登录");
}

结果为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值