java中Cookie使用問題(message:invalid character [32] was present in the Cookie value)


1、 問題描述

Servlet中執行下面一段代碼:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println( new Date().toString()); Cookie cookie = new Cookie("lasttime",  new Date().toString()); response.addCookie(cookie); String s = "歡迎您首次訪問該網站!~"; Cookie[] cookies = request.getCookies(); if (cookies != null) for (Cookie cs : cookies) { if (cs.getName().equals("lasttime")) { s = "您上次登錄的時間為:" + cs.getValue().replace("-", " "); } } response.getWriter().print(s); }

拋出如下異常:

 

2、 追根溯源

出現上述問題覺得很奇怪,因為程序編譯通過,至少證明沒有語法錯誤,根據編譯器提示,定位問題到:

Cookie cookie = new Cookie("lasttime", new Date().toString()); response.addCookie(cookie);

查看JAVAEE-API,發現有如下

回過去看代碼,發現

輸入:

System.out.println( new Date().toString());
輸出:

Fri Apr 20 21:56:39 CST 2018

很明顯輸出字符串中存在 空格 ,所以程序會報錯,存在無效字符。

 

3、解決方案

解決問題的方法其實很簡單,只要字符串中不存在空格即可成功,下面將給出幾種具體的解決辦法,程序修改如下:

法一

思路:用“-”代替“ ”,之后記得換回來即可,程序成功運行。 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println( new Date().toString()); Cookie cookie = new Cookie("lasttime",  new Date().toString().replace(" ", "-")); cookie.setMaxAge(60*60); response.addCookie(cookie); String s = "歡迎您首次訪問該網站!~"; Cookie[] cookies = request.getCookies(); if (cookies != null) for (Cookie cs : cookies) { if (cs.getName().equals("lasttime")) { s = "您上次登錄的時間為:" + cs.getValue().replace("-", " "); } } response.getWriter().print(s); }

法二

思路:進行URL編碼,然后把編碼后的字符串放到Cookie中,之后進行URL解碼即可。 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); System.out.println( new Date().toString()); Cookie cookie = new Cookie("lasttime", URLEncoder.encode(new Date().toString(), "UTF-8")); cookie.setMaxAge(60*60); response.addCookie(cookie); String s = "歡迎您首次訪問該網站!~"; Cookie[] cookies = request.getCookies(); if (cookies != null) for (Cookie cs : cookies) { if (cs.getName().equals("lasttime")) { s = "您上次登錄的時間為:" + URLDecoder.decode(cs.getValue(), "UTF-8"); } } response.getWriter().print(s); }

程序運行正常,符合預期值。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM