1.创建index.jsp文件,在该文件中,首先获取cookie对象的集合,如果集合不为空,就通过for循环遍历cookie集合,从中找出设置的cookie(这里设置为mrCookie),并从该cookie中提取出用户名和注册时间。
<%@page import="java.net.URLDecoder" %>
<%
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 %>
<%
}
%>
2、编写deal.jsp文件,用于向cookie中写入注册信息。deal.jsp文件的具体代码如下:
<%@ page language="java" import="java.util.*,java.net.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'deal.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</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>