Implementing Unified Functionality in Spring Boot: Authentication, Data Formatting, Exception Handling, and Interceptors
This article demonstrates how to build a unified processing module in Spring Boot by using AOP and HandlerInterceptor to centralize user login validation, standardize response formats, handle exceptions globally with @ControllerAdvice, and configure path prefixes, providing complete code examples and implementation details.
The tutorial introduces a Spring Boot unified functionality module that consolidates three core goals: user login permission verification, uniform data format responses, and centralized exception handling.
1. User Login Permission Validation – Initially, each controller method manually checks the session, leading to duplicated code and high maintenance cost. The article shows the original repetitive code and explains its drawbacks.
To solve this, Spring AOP is considered, but it cannot directly access HttpSession and cannot easily exclude specific endpoints such as login and registration.
2. Spring Interceptor Solution – The article proposes using HandlerInterceptor with a custom LoginInterceptor that implements preHandle to check the session and return a 401 status when the user is not authenticated. The interceptor is then registered in a WebMvcConfigurer implementation, where addPathPatterns("/**") intercepts all requests and excludePathPatterns excludes login, registration, and static resources.
Code example for the interceptor:
package com.example.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
return true;
}
log.error("Current user has no access permission");
response.setStatus(401);
return false;
}
}Configuration to add the interceptor:
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/user/login", "/user/reg");
}
}3. Unified Exception Handling – Using @ControllerAdvice together with @ExceptionHandler to catch generic and specific exceptions and return a consistent JSON structure. Example code shows handling of Exception and ArithmeticException with custom error codes and messages.
4. Unified Data Return Format – The article explains two approaches: a global ResponseBodyAdvice that wraps every response into a standard JSON object, and a softer approach using a custom AjaxResult utility class with static success and fail methods. Sample implementations of both are provided.
Finally, the article includes a brief discussion of the underlying Spring MVC mechanisms ( DispatcherServlet, applyPreHandle, etc.) and shows how @ControllerAdvice is processed during bean initialization.
Overall, the guide offers a complete, step‑by‑step solution for centralizing authentication, response formatting, and error handling in a Spring Boot backend application.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.
