【javaweb】【Session】记录用户访问时间
效果
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>
参考
版 权 声 明
作者:萌狼蓝天
QQ:3447902411(仅限技术交流,添加请说明方向)
转载请注明原文链接:https://www.cnblogs.com/zwj/p/javaweb_session_20211228.html