------------------------------------------------------------------------------------------
package cookie;
import java.io.IOException;
import java.io.PrintWriter;
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;
//代表网站首页
public class Cookie1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw=response.getWriter();
pw.write("您上次访问时间是:");
//获得用户的时间cookie
Cookie[] cookie=request.getCookies();
for(int i=0;cookie!=null && i<cookie.length;i++){
if(cookie[i].getName().equals("lastAccessTime")){
Long c=Long.parseLong(cookie[i].getValue());
Date date=new Date(c);
pw.print(date.toLocaleString());
}
}
//给用户会送最新的访问时间
Cookie newcookie= new Cookie("lastAccessTime",System.currentTimeMillis()+"");
newcookie.setMaxAge(1*30*24*3600*12);
newcookie.setPath("/servletdemo");
response.addCookie(newcookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}