2018-06-22Tomcat之cookie、session

cookie的购物.png
购物过程.png
显示上次访问时间.png
session.png
session域.png
//格式化时间格式
        Date date=new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String currentTime = format.format(date);
        //服务器向客户端浏览器写cookie
        Cookie cookie=new Cookie("LastAccessTime", currentTime);
        cookie.setMaxAge(10*60*50);
        response.addCookie(cookie);
        //客户端从浏览器客户端读取请求中的cookie
        String cookieValue=null;
        Cookie[] cookies = request.getCookies();
             //判断是否有我们需要的cookie
        if(cookies!=null) {
            for (Cookie cookie1 : cookies) {
                if(("LastAccessTime").equals(cookie1.getName())) {
                     cookieValue = cookie1.getValue();
                }
            }
        }
            //因为要在页面输入中文,所以要先设置编码格式
        response.setCharacterEncoding("utf-8");
        if(cookieValue!=null) {
            response.getWriter().write(cookieValue);
        }else {
            response.getWriter().write("恭喜您,是第一次访问我们的网站!");
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容