Cookie进行会话时出现的不合法字符问题

本文详细解析了在使用JSP与Tomcat 9.0环境下,遇到的Cookie值中包含非法字符(空格)的问题,并提供了解决方案,通过替换日期格式化方法,成功避免了非法字符的出现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天学习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>

运行后结果:
在这里插入图片描述
完工!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值