一、简介
WebMvcConfigurer配置类其实是Spring
内部的一种配置方式,采用JavaBean
的形式来代替传统的xml
配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer
接口;
在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐),方式二继承WebMvcConfigurationSupport类
二、接口
public interface WebMvcConfigurer {void configurePathMatch(PathMatchConfigurer var1);void configureContentNegotiation(ContentNegotiationConfigurer var1);void configureAsyncSupport(AsyncSupportConfigurer var1);void configureDefaultServletHandling(DefaultServletHandlerConfigurer var1);void addFormatters(FormatterRegistry var1);void addInterceptors(InterceptorRegistry var1);void addResourceHandlers(ResourceHandlerRegistry var1);void addCorsMappings(CorsRegistry var1);void addViewControllers(ViewControllerRegistry var1);void configureViewResolvers(ViewResolverRegistry var1);void addArgumentResolvers(List<HandlerMethodArgumentResolver> var1);void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> var1);void configureMessageConverters(List<HttpMessageConverter<?>> var1);void extendMessageConverters(List<HttpMessageConverter<?>> var1);void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> var1);void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> var1);Validator getValidator();MessageCodesResolver getMessageCodesResolver();
}
其中,常用的是
/* 拦截器配置 */
void addInterceptors(InterceptorRegistry var1);
/* 视图跳转控制器 */
void addViewControllers(ViewControllerRegistry registry);
/***静态资源处理
**/
void addResourceHandlers(ResourceHandlerRegistry registry);
/* 默认静态资源处理器 */
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
/*** 这里配置视图解析器**/
void configureViewResolvers(ViewResolverRegistry registry);
/* 配置内容裁决的一些选项*/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;
1、addInterceptors拦截器
- addInterceptor:需要一个实现HandlerInterceptor接口的拦截器实例
- addPathPatterns:用于设置拦截器的过滤路径规则;
addPathPatterns("/**")
对所有请求都拦截 - excludePathPatterns:用于设置不需要拦截的过滤规则
@Override
public void addInterceptors(InterceptorRegistry registry) {super.addInterceptors(registry);registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**").excludePathPatterns("/emp/toLogin","/emp/login","/js/**","/css/**","/images/**");
}
2、addCorsMappings跨域
@Override
public void addCorsMappings(CorsRegistry registry) {super.addCorsMappings(registry);registry.addMapping("/cors/**").allowedHeaders("*").allowedMethods("POST","GET").allowedOrigins("*");
}