public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获得用户请求的时候,封装在request中的cooike信息
Cookie[] cookies = request.getCookies();
// 遍历cookie数组
Cookie targetCookie = findTargetCookie(cookies, "lastvisit");
response.setContentType("text/html;charset=utf-8");
if (targetCookie == null) {
response.getWriter().print("您第一次来!!");
} else {
String strTime = targetCookie.getValue();
long time = Long.parseLong(strTime);
Date dateTime = new Date(time);
response.getWriter().print("您上次的访问时间是:"+dateTime.toLocaleString() );
}
//写出时间
Cookie cook = new Cookie("lastvisit",System.currentTimeMillis()+"");
response.addCookie(cook);
}
private Cookie findTargetCookie(Cookie[] cookies, String name) {
// TODO Auto-generated method stub
if (cookies == null) {
// null
return null;
}
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
// 找到目标cookie
return cookie;
}
}
return null;
}