1. 程式人生 > >java cookie案例分析-顯示上次登陸時間

java cookie案例分析-顯示上次登陸時間

案例描述: 在第一次登陸瀏覽某網站時顯示“第一次瀏覽”,在以後的每次瀏覽都顯示 上次瀏覽的時間

程式碼示例

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);
        }
    }
}