JavaNote 4.4 servlet实现记录网站上次访问时间

一、servlet

package com.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@WebServlet(name = "TimeServlet", urlPatterns = "/getTime")
public class TimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Date date = new Date();
        //格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd:hh:mm:ss");
        String format = dateFormat.format(date);
        //将格式化过的日期添加进cookie
        Cookie cookie = new Cookie("Time", format);
        response.addCookie(cookie);
        //第一次请求是不带cookie的所以timeValue为null,第二次请求时是带着cookie请求的
        String timeValue = null;
        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        for (Cookie cookie1 : cookies) {
            if (cookie1.getName().equals("Time")) {
                timeValue = cookie1.getValue();
            }
        }
        if (timeValue == null) {
            response.getWriter().write("欢迎您访问我们的网站");
        } else {
            response.getWriter().write("你上次访问的时间是" + timeValue);

        }
    }
}

 

你可能感兴趣的:(Java,Note)