效果

1.jpg

2.jpg

3.jpg

Servlet

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.util.Date;

@WebServlet(name = "Login", value = "/login")
public class ServletLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession st =request.getSession();
        if(st.getAttribute("LoginTime")==null){
            response.getWriter().println("首次登陆");
        }else{
            response.getWriter().println("上次登陆时间 | "+request.getSession().getAttribute("LoginTime"));
        }

        st.setAttribute("LoginTime", new Date());
        st.setMaxInactiveInterval(60*60);
        response.getWriter().println("<br/>现在登陆时间 | "+request.getSession().getAttribute("LoginTime"));
    }
}
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.util.Date;

@WebServlet(name = "Login", value = "/login")
public class ServletLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession st =request.getSession();//获取Session
        if(st.getAttribute("LoginTime")==null){//判断是否有需要的内容
            //如果为null,说明是首次访问
            response.getWriter().println("首次登陆");
        }else{
            //如果不为null,说明访问过了
            response.getWriter().println("上次登陆时间 | "+request.getSession().getAttribute("LoginTime"));//通过request获取上次访问时间
        }

        st.setAttribute("LoginTime", new Date());//记录这次新的访问时间
        st.setMaxInactiveInterval(60*60);//设置Session有效时间 单位为秒
        response.getWriter().println("<br/>现在登陆时间 | "+request.getSession().getAttribute("LoginTime"));
    }
}

JSP

<%--
  Created by IntelliJ IDEA.
  User: xrilang
  Date: 28/12/2021
  Time: 10:43
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/login">go</a>
  </body>
</html>

参考

Java设置Session

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐