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 CookieDemo1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置response的字符编码
response.setCharacterEncoding("UTF-8");
//控制浏览器以相同的编码打开
response.setContentType("text/html;charset=UTF-8");
//向浏览器写数据
PrintWriter out = response.getWriter();
out.print("您上次访问的时间是:");
//获得用户的时间cookie
Cookie[] cookies = request.getCookies();
//cookies不等于null
for(int i = 0;cookies!=null && i < cookies.length;i++){
//如果cookie是我们要的cookie
if(cookies[i].getName().equals("lastAccessTime")){
//得到值
long cookieValue = Long.parseLong(cookies[i].getValue());
Date date = new Date(cookieValue);
out.print(date.toLocaleString());
}
}
//给用户回送最新的访问时间
//1,创建cookie设置cookie名和值
Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
//2,设置cookie的有效期
//设置cookie有效期为一个月,值的单位是秒
cookie.setMaxAge(1*30*24*3600);
//3,设置cookie的路径
//只要是当前网站下的访问路径,都取cookie
cookie.setPath("/day07");
response.addCookie(cookie);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}