解决response.addCookie()报错

解决response.addCookie()报错

今天写cookie时遇到错误

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

一个不识别的字符[32]出现在了cookie当中
由于tomcat的版本比较高,所以在addCookie时是不能使用空格的 而在ASCII码中32对应的就是空格。只要把后台代码中的空格删掉就可以了。

下面是我的代码:()
解决办法:只需要把时间格式那里的空格去掉,我改成了"-",成功解决

 //处理响应中文的乱码问题
		response.setContentType("text/html;charset=utf-8");
	    //1.获取所有cookie
		Cookie[] cookies=request.getCookies();
	    //2.遍历cookie数组
		String lastTime=null;
		for(int i=0;cookies!=null&&i<cookies.length;i++) {
			//3.获取cookie的名称
			String name=cookies[i].getName();
			if("lastAccess".equals(name)) {
				//获取cookie的时间
			 lastTime=cookies[i].getValue();
			}
		}
		//3.判段是否是首次访问,如果cookie里有时间,就不是第一次访问,否则就是第一次访问
		if(lastTime==null) {
			//第一次访问:
			response.getWriter().print("first");
		}else {//说明不是第一次访问
		//把上次访问的时间回写到浏览器
			response.getWriter().print("lasttime:"+lastTime);
		}
		//第三次,第四次---
		Date date = new Date();
		//下面这个日期格式不能出现空格
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
        String currentTime = format.format(date);
        Cookie cookie = new Cookie("lastAccess",currentTime);
        cookie.setMaxAge(60*60*10);
        response.addCookie(cookie);

参考链接:https://blog.csdn.net/caopengflying/article/details/78965733

猜你喜欢

转载自blog.csdn.net/qq_43753724/article/details/105336755