1. index.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//从request中获得cookie对象
Cookie[] cookies=request.getCookies();
//登录用户
String user="";
//注册的时间
String date="";
if(cookies!=null){
//遍历cookie对象的集合
for(int i=0;i<cookies.length;i++){
//如果cookie对象的名称为mrCookie
if(cookies[i].getName().equals("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 %>
<%
}
%>
</body>
</html>
2. deal.jsp
<%@page import="java.net.URLEncoder"%>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String user =URLEncoder.encode(request.getParameter("user")) ;
String info=user+"#"+new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
//创建并实例化cookie对象
Cookie cookie =new Cookie("mrCookie",info);
//设置有效期30天
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
%>
<script type="text/javascript">
window.location.href="index.jsp"
</script>
</body>
</html>
3.效果图