zoukankan      html  css  js  c++  java
  • Cookie实战案例代码

    import java.io.IOException;
    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;
    /**
     * 例-用户上次访问时间
     * @author APPle
     *
     */
    public class HistServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            //cookie的有效路径。默认情况:有效路径在当前web应用下。 
            //获取当前时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String curTime = format.format(new Date());
            
            
            //取得cookie
            Cookie[] cookies = request.getCookies();
            String lastTime = null;
            if(cookies!=null){
                for (Cookie cookie : cookies) {
                    if(cookie.getName().equals("lastTime")){
                        //有lastTime的cookie,已经是第n次访问
                        lastTime = cookie.getValue();//上次访问的时间
                        //第n次访问
                        //1.把上次显示时间显示到浏览器
                        response.getWriter().write("欢迎回来,你上次访问的时间为:"+lastTime+",当前时间为:"+curTime);
                        //2.更新cookie
                        cookie.setValue(curTime);
                        cookie.setMaxAge(1*30*24*60*60);
                        //3.把更新后的cookie发送到浏览器
                        response.addCookie(cookie);
                        break;
                    }
                }
            }
            
            /**
             * 第一次访问(没有cookie 或 有cookie,但没有名为lastTime的cookie)
             */
            if(cookies==null || lastTime==null){
                //1.显示当前时间到浏览器
                response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime);
                //2.创建Cookie对象
                Cookie cookie = new Cookie("lastTime",curTime);
                cookie.setMaxAge(1*30*24*60*60);//保存一个月
                //3.把cookie发送到浏览器保存
                response.addCookie(cookie);
            }
        }
    
    }
  • 相关阅读:
    在线|九月月考选填题
    函数$f(x)=e^xpm e^{-x}$相关
    偶函数性质的推广
    2020年全国卷Ⅱ卷文科数学选填题解析版
    2020年全国卷Ⅱ卷文科数学解答题解析版
    待定系数法
    特殊方法求函数解析式
    phd文献阅读日志-4.1
    phd文献阅读日志-1.2~3.2(1.2,2.1,2.2,3.1,3.2)
    完美解决linux下vim在终端不能用鼠标复制的问题
  • 原文地址:https://www.cnblogs.com/loaderman/p/9999300.html
Copyright © 2011-2022 走看看