Cookie進行會話時出現的不合法字符問題

今天學習JSP中獲取Cookie代碼時,碰到了如下問題:
deal6.4代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.net.URLEncoder" %>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>寫入cookie</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");				//設置請求的編譯爲UTF-8
String user=URLEncoder.encode(request.getParameter("user"),"UTF-8");//獲取用戶名
Cookie cookie = new Cookie("lgCookie",user+"#"+new java.util.Date().toLocaleString());//創建並實例化cookie對象
cookie.setMaxAge(60*60*24*30);							//設置cookie有效期30天
response.addCookie(cookie);						//保存cookie
%>
<script type="text/javascript">window.location.href="index6.4.jsp"</script>
</body>
</html>

運行後錯誤如下:
在這裏插入圖片描述
其中Root Cause下面一行的錯誤提示爲:java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value ,查詢資料得知根本原因:tomcat9.0中cookie不接受非法字符,非法字符,如堆棧中所述,[32],可以查詢32對應的ASCII碼,如此處是:空格。

所以肯定有哪個地方在給cookie賦值時出現空格,逐條代碼分析發現new java.util.Date().toLocaleString()這句中有空格輸出,故將其替換成其他代碼

新修改後的代碼:

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.net.URLEncoder" %>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>寫入cookie</title>
</head>
<body>
<%
Date date = new Date();
SimpleDateFormat dtf = new SimpleDateFormat("h:m:s");
request.setCharacterEncoding("UTF-8");				//設置請求的編譯爲UTF-8
String user=URLEncoder.encode(request.getParameter("user"),"UTF-8");//獲取用戶名
Cookie cookie = new Cookie("lgCookie",user+"#"+dtf.format(date));//創建並實例化cookie對象
System.out.println(dtf.format(date));
cookie.setMaxAge(60*60*24*30);							//設置cookie有效期30天
response.addCookie(cookie);						//保存cookie
%>
<script type="text/javascript">window.location.href="index6.4.jsp"</script>
</body>
</html>

運行後結果:
在這裏插入圖片描述
完工!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章