Implementing Login Interception in SpringBoot Using HandlerInterceptor and WebMvcConfigurer
This article explains how to secure a SpringBoot web application by creating a login interceptor with the HandlerInterceptor interface, registering it via WebMvcConfigurer, managing user sessions, and demonstrates the complete code and verification steps to ensure authenticated access.
For management systems or any application that requires user authentication, login validation is essential. In a SpringBoot project, this can be achieved by implementing an interceptor that checks the user session before allowing access to controller methods.
1. Principle of SpringBoot Login Interception
SpringBoot uses the HandlerInterceptor interface to create an interceptor and the WebMvcConfigurer interface to register it in a configuration class, which is then injected with @Configuration .
1.1 Implementing HandlerInterceptor
The HandlerInterceptor interface requires three methods:
preHandle
postHandle
afterCompletion
These methods are used to perform actions before the controller, after the controller but before view rendering, and after the request completes, respectively.
package blog.interceptor;
import blog.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class UserLoginInterceptor implements HandlerInterceptor {
/***
* Called before the controller method execution.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行了拦截器的preHandle方法");
try {
HttpSession session = request.getSession();
// Check if a user object exists in the session
User user = (User) session.getAttribute("user");
if (user != null) {
return true;
}
response.sendRedirect(request.getContextPath() + "login");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/***
* Called after the controller method but before view rendering.
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("执行了拦截器的postHandle方法");
}
/***
* Called after the request has been completed and the view rendered.
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行了拦截器的afterCompletion方法");
}
}The preHandle method checks whether a user object is stored in the session; if present, it returns true to allow the request to proceed, otherwise it redirects to the login page.
1.2 Registering the Interceptor with WebMvcConfigurer
Implement WebMvcConfigurer to create a configuration class that registers the interceptor and defines which URL patterns should be intercepted or excluded.
package blog.config;
import blog.interceptor.UserLoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Register the UserLoginInterceptor
InterceptorRegistration registration = registry.addInterceptor(new UserLoginInterceptor());
registration.addPathPatterns("/**"); // Intercept all paths
registration.excludePathPatterns(
"/login", // Login page
"/**/*.html", // Static HTML
"/**/*.js", // Static JS
"/**/*.css" // Static CSS
);
}
}After registration, all requests are intercepted except the login page and static resources.
2. Code Implementation and Example
Controller methods store the authenticated user in the session after a successful login, allowing subsequent requests to bypass the login interceptor.
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET)
public String index(Model model, HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
model.addAttribute("user", user);
return "users/index";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginIndex() {
return "users/login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam(name = "username") String username,
@RequestParam(name = "password") String password,
Model model, HttpServletRequest request) {
User user = userService.getPwdByUsername(username);
String pwd = user.getPassword();
String password1 = MD5Utils.md5Code(password).toUpperCase();
String password2 = MD5Utils.md5Code(password1).toUpperCase();
if (pwd.equals(password2)) {
model.addAttribute("user", user);
request.getSession().setAttribute("user", user);
return "redirect:/index";
} else {
return "users/failed";
}
}When the user logs in successfully, the user object is saved in the session; subsequent accesses find this object and skip the login page.
3. Effect Verification
3.1 Accessing localhost:8081/index
The request is redirected to localhost:8081/login , confirming that the interceptor blocks unauthenticated access.
3.2 Logging in with correct credentials
After a successful login, the user is redirected to the index page.
3.3 Re‑accessing localhost:8081/index
No redirection occurs, demonstrating that the login state is preserved via the session.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.