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

来源:互联网 发布:api原油库存数据预测 编辑:程序博客网 时间:2024/05/18 12:30

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

问题

    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);        }

结果如图:
第一次访问:
这里写图片描述

非第一次访问:
这里写图片描述

阅读全文
0 0