java - 在servlet中加入cookie報錯
滿天的星座
滿天的星座 2017-06-15 09:22:04
0
1
1135

1.在加入cookie的時候報錯:

An invalid character [13] was present in the Cookie value
  1. 在網路上查了一些報錯,大部分都是[32]、[44],據說是因為cookie裡面加了「,」或空格導致的。

  2. 登陸處理的程式碼是這樣的:

//登录处理
    @RequestMapping(value = "/login/validate", method = RequestMethod.POST)
    public void Validate(@RequestParam("username") String username, @RequestParam("password") String password,
                         HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String md5 = MD5Util.stringToMD5(password);
        if (userService.verification(username, md5)) {
            User user = userService.selectByUsername(username);
            Long id = user.getId();
            Long createDate = new Date().getTime();
            String str = id + "=" + createDate;
            //加密
            byte[] result = DESUtil.desCrypto(str, "12345678");

            //把加密的字节数组转换成16进制
//            String results = TypeUtil.bytesToHexString(result);
            String results = Base64.encodeBase64String(result);

            Cookie cookie = new Cookie("token", results);
            cookie.setMaxAge(60 * 60 * 24 * 7);//7天
            cookie.setPath("/");
            System.out.println("新生成cookie和其MaxAge:" + cookie.getName() + "-->" + cookie.getMaxAge());
            httpServletResponse.addCookie(cookie);
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("user", user);
            for (Cookie c : httpServletRequest.getCookies()) {
                System.out.println("cookes添加到response后重新获取cookies和其MaxAge:" + c.getName() + "-->" + c.getMaxAge());
            }
            try {
                httpServletResponse.sendRedirect("/index.html");
//                httpServletRequest.getRequestDispatcher("/index.html").forward(httpServletRequest, httpServletResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                httpServletResponse.sendRedirect("no.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

報錯的地方發生在addCookie這裡。

滿天的星座
滿天的星座

全部回覆(1)
代言

經過嘗試,把原來的程式碼2註釋,1 放開就可以了,哪位大佬可以解釋一下啊

1. String results = TypeUtil.bytesToHexString(result);
2. //String results = Base64.encodeBase64String(result);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板