Java.Servlet.What is an effective way to ensure that all servlets are accessible only to a user with a valid session?

Short answer:
The most effective and standard way is to use a Servlet Filter.

  • A Filter intercepts every request before it reaches the servlet.
  • In the filter, you check if the user has a valid session.
  • If the session is missing or invalid, you redirect them to the login page.
  • Otherwise, you allow the request to continue to the servlet.

How to implement it step-by-step:

  1. Create a Filter class.
  2. In the doFilter() method:
    • Check if the session exists.
    • Check if the session has a specific attribute (like user or authenticated flag).
    • If not → redirect to login page.
    • If yes → continue the request (chain.doFilter()).

Example code:

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

// Apply this filter to all URLs ("/*")
@WebFilter("/*")
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession(false); // false = don't create a new session
        
        String loginURI = req.getContextPath() + "/login.jsp";

        boolean loggedIn = (session != null) && (session.getAttribute("user") != null);
        boolean loginRequest = req.getRequestURI().equals(loginURI);

        if (loggedIn || loginRequest) {
            // User is logged in or trying to access login page — let them through
            chain.doFilter(request, response);
        } else {
            // Not logged in — redirect to login page
            res.sendRedirect(loginURI);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) { }

    @Override
    public void destroy() { }
}

Explanation:

  • @WebFilter("/*") → filter applies to all URLs.
  • session.getAttribute("user") → we assume you set some user attribute after successful login.
  • If the session is missing or attribute is missing → block access and redirect to login.

Typical login code for reference:

When user successfully logs in:

HttpSession session = request.getSession();
session.setAttribute("user", username);

(You can set any object, like a User object.)

Bonus Tip:
You might want to exclude static resources (CSS, JS, images) from filtering, or it will block them too!

You can add a check like:

boolean resourceRequest = req.getRequestURI().startsWith(req.getContextPath() + "/resources/");

if (loggedIn || loginRequest || resourceRequest) {
    chain.doFilter(request, response);
} else {
    res.sendRedirect(loginURI);
}

Or configure it smarter with URL patterns.

Alternative approaches (more advanced):

  • Use Java EE security (declarative, via web.xml) — <security-constraint>.
  • Use Spring Security if you use Spring Boot / Spring MVC.
  • But for a simple servlet app, Filter is the cleanest and most flexible solution.
MethodWhen to use
FilterBest for servlet apps, flexible control
web.xml <security-constraint>OK but less flexible, older style
Spring SecurityFor Spring Boot / complex apps
This entry was posted in Без рубрики. Bookmark the permalink.