通过Request对象对cookie的设置、获取

时间:2023-03-09 00:00:51
通过Request对象对cookie的设置、获取
<html>
<head></head>
<body> <%
request.setCharacterEncoding("UTF-8");
String user = URLEncoder.encode(request.getParameter("user"),"UTF-8");
Cookie cookie = new Cookie("zwqCookie",user+"#"+new java.util.Date().toString());
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
%>
<script type = "text/javasript">window.location.href="index.jsp"</script>
</body>
</html>

 通过request对象将获得的user值使用UTF-8编码后,与日期一起拼接成一个cookie,并设置cookie的最大有效期为30天,然后通过Response回送cookie到浏览器

使用script脚本代码来让浏览器回到index主页

在主页执行如下代码

<%
Cookie cookie = request.getCookie();
String user = "";
String date = "";
if(cookie!=null){
for(int i=0;i<cookie.length;i++){
if(cookie[i].getName().equals(zwqCookie)){
user = URLDecoder.decode(cookies[i].getValue().split("#")[0],"UTF-8");
<!--在这里应该指定字符集为UTF-8否则不能得到中文下的user-->date = cookie[i].getValue().split("#")[0]; } } } %>