How to create a Spring Boot interceptor
To create a Spring Boot interceptor, you need to follow these steps:
- An interceptor for handling requests.
- Before handling the request
- manage()
- onceFinished()
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理之前进行调用(Controller方法调用之前)
return true; // 如果返回false,则请求中断
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)
}
}
- Configurable web MVC adapter
- include interceptors
- Set up or configuration
- Activate WebMvc
- Override the following
- includeInterceptors()
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/**");
// 添加自定义拦截器,并设置拦截路径,这里设置拦截所有请求
}
}
In this way, you have created a simple Spring Boot interceptor. When a request enters the application, the interceptor’s preHandle() method is called, and then decides whether to interrupt the request based on the return value; after the request is processed, the interceptor’s postHandle() method is called, executed before view rendering; finally, after the entire request is completed, the interceptor’s afterCompletion() method is called for resource cleanup.