关于拦截器 Interceptor
是什么,以及如何在 SpringBoot 中配置拦截器
拦截器
- 拦截器(
Interceptor
)在 Spring MVC 框架中是一个重要的组件。
- 拦截器,就是可以拦截 Http 请求,进行一些处理后,再传递给 controller 层进行处理。所以可以在处理 HTTP 请求的过程中进行一些 == 预处理和后处理 ==。例如,你可以在一个拦截器中检查用户是否已经登录,或者记录请求的处理时间。
- 处理流程(Http):拦截器 –> Controller –> Service –> data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("Pre Handle method is Calling"); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Post Handle method is Calling"); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { System.out.println("Request and Response is completed"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration public class AppConfig implements WebMvcConfigurer {
@Autowired private MyInterceptor myInterceptor;
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor); } }
|