Currently, I find that the user is logged out by searching for null attributes
This is also a normal approach. To verify that the user is logged in, you must not check if the session servlet container is created or not. This is not a registered user at all.
When entering the system, simply place the user model object in the session area without checking whether the container has created a session for you. In other words, just use getSession() without a boolean argument, so that the container automatically locks if necessary, you need a session at this point:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = userService.find(username, password); if (user != null) { request.getSession().setAttribute("user", user); response.sendRedirect(request.getContextPath() + "/home"); } else { request.setAttribute("message", "Unknown login. Please retry."); request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); } }
When filtering access, just check if there is a session attribute representing the logged in user, use getSession(false) here to avoid unnecessary session creation, otherwise, for example, search bots would initiate a session creation, which is completely unnecessary:
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); User user = (session != null) ? (User) session.getAttribute("user") : null; String loginURL = request.getContextPath() + "/login"; if (user == null && !request.getRequestURI().equals(loginURL)) { response.sendRedirect(loginURL); } else { chain.doFilter(request, response); } }
When logging out, make sure you send the redirect after the invalidation, as the current session is still available in the redirect response.
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().invalidate(); response.sendRedirect(request.getContextPath() + "/login"); }