SpringMVC-添加拦截器
添加拦截器
- 1、MyInterceptor-定义一个拦截器
- 2、WebMvcConfiguration-定义配置类,注册拦截器
拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。在SpringBoot官方文档中有这么一段说明:
- 如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现WebMvcConfigurer,并且添加@Configuration注解。如果你想要自定义HandlerMapping、HandlerAdapter、ExceptionResolver等组件,你可以创建一个WebMvcRegistrationsAdapter实例 来提供以上组件。
总结:通过实现WebMvcConfigurer并添加@Configuration注解来实现自定义部分SpringMvc配置。
实现如下:
1、MyInterceptor-定义一个拦截器
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle method is running!");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle method is running!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion method is running!");
}
}
@Component
- 在WebMvcConfiguration实现类中用到了@Autowired注解,被注解的这个类是从Spring容器中取出来的,那调用的这个类也需要被Spring容器管理,加上@Component把普通pojo实例化到spring容器中
2、WebMvcConfiguration-定义配置类,注册拦截器
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
@Autowired
private HandlerInterceptor myInterceptor;
/** * 重写接口中的addInterceptors方法,添加自定义拦截器 * @param registry */
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
还没有评论,来说两句吧...