package com.itheima.cookie.app1;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
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;
//显示用户最近访问的一次时间:lastAccessTime=485784395
public class CookieDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
System.out.println("您上次访问的时间是:");
out.write("您上次访问的时间是:");
//获取名为lastAccessTime的Cookie
//取出它的值,并打印在页面上
Cookie[] cs = request.getCookies();
for(int i=0;cs!=null&&i<cs.length;i++){
Cookie c=cs[i];
if("lastAccessTime".equals(c.getName())){
String value=c.getValue();//时间为毫秒值
Date time=new Date(Long.parseLong(value));
DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out.write(df.format(time));
}
}
//把最新的时间写回去
Cookie c=new Cookie("lastAccessTime", System.currentTimeMillis()+"");
response.addCookie(c);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
|