How can interceptors be implemented in Spring Boot?
There are two ways to implement interceptors in Spring Boot.
- Implementing the HandlerInterceptor interface: Create a class that implements the HandlerInterceptor interface, then implement its preHandle, postHandle, and afterCompletion methods, used for handling requests before, after, and upon completion. Finally, register the interceptor in the configuration class.
The example code is as follows:
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理前进行拦截处理
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在请求处理后进行拦截处理
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在请求完成后进行拦截处理
}
}
Register the interceptor in the configuration class.
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
- Extend the HandlerInterceptorAdapter class: Create a class that extends the HandlerInterceptorAdapter class, then override its preHandle, postHandle, and afterCompletion methods, and register the interceptor in the configuration class.
The sample code is shown below:
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求处理前进行拦截处理
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在请求处理后进行拦截处理
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在请求完成后进行拦截处理
}
}
Interceptors can also be registered in the configuration class using the addInterceptors method.