具体步骤如下 :
- 编写一个拦截器
- 通过WebMvcConfigurer注册拦截器
1.编写一个拦截器类并实现HandlerInterceptor
@Component
public class HelloInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("HelloInterceptor - preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("HelloInterceptor - postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("HelloInterceptor - afterCompletion");
}
}
2.通过WebMvcConfigurer注册拦截器
@SpringBootConfiguration
public class MVCInterceptorConfig implements WebMvcConfigurer {
@Autowired
HelloInterceptor helloInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(helloInterceptor).addPathPatterns("/**");
}
}
|