用Cookie实现显示上一次访问的时间和删除cookie

时间:2018-01-10
public class Cookie1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html;charset=utf-8");
         PrintWriter out = response.getWriter();
         //得到客户端的所有的Cookie 
         Cookie[] cookies=request.getCookies();
         //从Cookie中找出存储最后登录时间的Cookie
         //Cookie是一个键值对,并且键和值都是String的
         if(cookies!=null){
             for(int i=0;i<cookies.length;i++){
                 String name = cookies[i].getName();//得到Cookie的name
                 if("lastAccessTime".equals(name))
                 {
                     String time = cookies[i].getValue();//得到最后登录时间,时间是字符串类型的
                     long  t = Long.parseLong(time);
                     out.println("上次登录时间为:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(t)));
                 }
             }
         }
         //在页面上写一个删除的链接连接到DelCookie上删除cookie
         out.println("<a href='"+request.getContextPath()+"/servlet/delcookie'>删除Cookie</a>");

         //把这次的登录时间以Cookie的形式发送给客户端
         //创建Cookie
         Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
         cookie.setMaxAge(60*15);//Cookie 被存储到磁盘了
         cookie.setPath(request.getContextPath());// /day35_cookie 只要是路径以 /day35_cookie开头的都可以接收到Cookie
         //cookie.setPath("/");//  /day35_cookie
         //把cookie发送给客户端
         response.addCookie(cookie);
         /*
          * Cookie默认存储在浏览器的内存,浏览器一旦关闭,Cookie全都没了
          * setMaxAge(time)设置Cookie的最大存活时间,默认单位是秒
          * setMaxAge(-1);默认是-1,浏览器一旦关闭,Cookie全都没了
          * setMaxAge(0):浏览器不关闭,Cookie也没了
          * setMaxAge(正数)
          * 
          * 满足什么条件客户端会把Cookie发给服务器端?
          * 被访问资源的路径前边要匹配  
          * http://localhost:8080/day35_cookie/servlet/cookie1
          * http://localhost:8080/day35_cookie/servlet/cookie2
          */
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


删除cookie:

public class DelCookie extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //删除Cookie
        Cookie cook = new Cookie("lastAccessTime", "");
        cook.setMaxAge(0);
        //设置path,否则可能会错删
        cook.setPath(request.getContextPath());
        response.addCookie(cook);       
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         doGet(request,response);
    }

}

上一条:javascript最新正则验证手机号码有效性 下一条:jQuery ajax使用$(this).parent()无效解决方法

相关文章

最新文章