code018.jsp
<%@page import="java.nio.charset.StandardCharsets"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page import="java.util.Date"%>
<%@ page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>写入cookie</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String user = URLEncoder.encode(request.getParameter("user"), "utf-8") ; //cookie中保存中文时,需要使用urlencode类的encode方法进行编码
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd@HH:mm:ss.SSS");
String value = user + "#" + format.format(date);
Cookie cookie1 = new Cookie("mycookie",value);
cookie1.setMaxAge(60*2); //2个60秒, 原书中为 60*60*24*30 一个月
response.addCookie(cookie1); //java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value[32]是空格,所以在代码里去除空格就行了。
%>
<script type="text/javascript">window.location.href="code017.jsp";</script>
</body>
</html>