import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* http://localhost:8080/day07/Demo2?name=jack回车
*/
public class Demo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String name = request.getParameter("name");
if(name==null){
name="default";
}
//取得客户端的所有Cookie的值
Cookie[] cookies = request.getCookies();
if(cookies==null){
Cookie cookie = new Cookie("name_"+name,System.currentTimeMillis()+"");
cookie.setMaxAge(1*24*60*60);
response.addCookie(cookie);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("欢迎"+name+"首次光临,访问时间:" + new Date().toLocaleString());
}else{
//查找名为name的Cookie
Cookie nameCookie = null;
for(Cookie c : cookies){
if(c.getName().equals("name_"+name)){
nameCookie = c;
break;
}
}
//找到了
if(nameCookie!=null){
String strTime = nameCookie.getValue();
response.setContentType("text/html;charset=UTF-8");
long lastTime = Long.parseLong(strTime);
response.getWriter().write("欢迎"+name+"再次光临,你上次访问时间:" + new Date(lastTime).toLocaleString());
//更新时间
Cookie cookie = new Cookie("name_"+name,System.currentTimeMillis()+"");
cookie.setMaxAge(1*24*60*60);
response.addCookie(cookie);
}
}
}
}
原文地址:http://blog.51cto.com/357712148/2105015
时间: 2024-11-14 00:07:22