java cookie案例分析-显示上次登陆时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITzhongzi/article/details/85774013

案例描述: 在第一次登陆浏览某网站时显示“第一次浏览”,在以后的每次浏览都显示 上次浏览的时间

代码示例

package com.wl.cookie;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SendCookieServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //获取当前时间并格式化
        Date date  = new Date();
        // 中间加一个  |  是因为  在cookie中不能存储 “ ”,不然会报错
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd|hh:mm:ss");
        String currentTime = simpleDateFormat.format(date);

        //将现在的时间存储到cookie中
        Cookie cookie = new Cookie("lastAccessTime", currentTime);
//        cookie.setMaxAge(10 * 60);
        cookie.setPath("/cookie");
        response.addCookie(cookie);

        //获取浏览器请求中 的cookie ,如果有 说明之前访问过,获取该时间并显示
        // 如果没有值,说明是第一次访问,显示欢迎界面
        String lastAccessTime = null;
        Cookie[] cookies = request.getCookies();
        if(cookie != null){
            for (Cookie c : cookies){
                if("lastAccessTime".equals(c.getName())){
                    lastAccessTime = c.getValue();
                }
            }
        }
        response.setContentType("text/html;charset=utf-8");
        if(lastAccessTime == null){
            response.getWriter().write("您是第一次访问");
        } else {
            response.getWriter().write("您上次的访问时间是" + lastAccessTime);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ITzhongzi/article/details/85774013