主要参考自:Java Web学习–获取Cookie报错An invalid character [32] was present in the Cookie value
最近学习Java web,参考《Java Web从入门到精通》,在学习第六章 JSP内置对象 时,遇到了一个问题,问题报错在response.addCookie(cookie);这一行,经查阅,忽略其他报错信息,关于问题有用的提示是:
An invalid character [32] was present in the Cookie value
通过Cookie保存并读取用户登录信息:
index.jsp源代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.net.URLDecoder" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>通过cookie保存并读取用户登录信息</title>
</head>
<body>
<%
Cookie[ ] cookies = request.getCookies();//从request中获得Cookie对象的集合
String user = ""; //登录用户
String date = ""; //注册的时间
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) { //遍历cookie对象的集合
if (cookies[i].getName().equals("mrCookie")) {//如果cookie对象的名称为mrCookie
user = URLDecoder.decode(cookies[i].getValue().split("#")[0]);//获取用户名
date = cookies[i].getValue().split("#")[1];//获取注册时间
}
}
}
if ("".equals(user) && "".equals(date)) {//如果没有注册
%>
游客您好,欢迎您初次光临!
<form action="deal.jsp" method="post">
请输入姓名:<input name="user" type="text" value="">
<input type="submit" value="确定">
</form>
<%
} else {//已经注册
%>
欢迎[<b><%=user %></b>]再次光临<br>
您注册的时间是:<%=date %>
<%
}
%>
</body>
</html>
deal.jsp源代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.net.URLEncoder" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>写入cookie</title>
<script type="text/javascript">window.location.href="index.jsp"</script>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String user=URLEncoder.encode(request.getParameter("user"),"utf-8"); //获取用户名
Cookie cookie = new Cookie("mrCookie", user+"#"+new java.util.Date().toLocaleString());
cookie.setMaxAge(60*60*24*30); //设置cookie有效期30天
response.addCookie(cookie); //保存cookie
%>
</body>
</html>
character [32] 对应的字符是空格,我的tomcat版本为9.0,故不能含有空格,通过查找,发现是:
new java.util.Date().toLocaleString()
这句中有空格输出,为此,修改此句的时间显示格式,消去空格即可
修改代码如下:
request.setCharacterEncoding("utf-8");
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
String time = dateFormat.format(date);
String user=URLEncoder.encode(request.getParameter("user"), "utf-8"); //获取用户名
Cookie cookie = new Cookie("mrCookie", user+"#"+time);
cookie.setMaxAge(60*60*24*30); //设置cookie有效期30天
response.addCookie(cookie); //保存cookie
再次运行,输入同户名qaq,正常显示!