您的位置:首页 > 产品设计 > UI/UE

关于Cookie的An invalid character [32] was present in the Cookie value异常

2017-07-23 15:34 387 查看

案例—显示用户上次登录时间

问题

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String nowtime=sdf.format(new Date());

Cookie cookie=new Cookie("lasttime", nowtime);

cookie.setMaxAge(3600*24*7);

response.addCookie(cookie);


这段代码的报的异常java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value。
经检查发现是response.addCookie(cookie);的cookie的值不能出现空格,就是说将SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");里格式的空格去掉就没问题。
也可以在获取当前登录时间时,使用URLEncoder编码,再设置为cookie的值;在获取cookie的value值的时候,使用URLDecoder解码。核心代码如下:


核心代码

使用javaweb实现:

//doGet内代码
//获得当前时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = format.format(date);
// 使用URLEncoder编码,防止cookie的value出现
// An invalid character [32] was present in the Cookie value异常
currentTime = URLEncoder.encode(currentTime, "UTF-8");

//1、创建Cookie 记录当前的最新的访问时间
Cookie cookie = new Cookie("lastAccessTime", currentTime);
cookie.setMaxAge(3600*24*7);
response.addCookie(cookie);

//2、获得客户端携带cookie ---- lastAccessTime
String lastAccessTime = null;
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for(Cookie coo : cookies){
if("lastAccessTime".equals(coo.getName())){
// 使用URLDecoder解码
lastAccessTime = URLDecoder.decode(coo.getValue(), "UTF-8");
}
}
}

response.setContentType("text/html;charset=UTF-8");
if(lastAccessTime==null){
response.getWriter().write("您是第一次访问");
}else{
response.getWriter().write("您上次的访问的时间是:"+lastAccessTime);
}


结果如图:

第一次访问:



非第一次访问:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cookie 异常 javaweb
相关文章推荐