java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value

主要参考自: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,正常显示!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值