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