In the recent project, due to code demolition, part of the code in project A was migrated to project B. The migrated code involved the interceptor, but the interceptor did not work after the migration. Later, it was found that the interceptor configuration class did not exist, that is , WebMvcConfigurer Without migration, a simple research on this class was conducted, which is summarized as follows.
The source code of WebMvcConfigurer is as follows:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.web.servlet.config.annotation;
import java.util.List;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
public interface WebMvcConfigurer {
default void configurePathMatch(PathMatchConfigurer configurer) {
}
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
default void addFormatters(FormatterRegistry registry) {
}
default void addInterceptors(InterceptorRegistry registry) {
}
default void addResourceHandlers(ResourceHandlerRegistry registry) {
}
default void addCorsMappings(CorsRegistry registry) {
}
default void addViewControllers(ViewControllerRegistry registry) {
}
default void configureViewResolvers(ViewResolverRegistry registry) {
}
default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
}
default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
}
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}
default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
}
default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}
default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}
@Nullable
default Validator getValidator() {
return null;
}
@Nullable
default MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
It contains a lot of methods, simply summarize the commonly used methods
/* 拦截器配置 */
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) ;
addInterceptors configure interceptors
addInterceptor: Add an interceptor instance that implements the HandlerInterceptor interface
addPathPatterns: Used to set the filtering path rules of the interceptor; addPathPatterns("/**") intercepts all requests
excludePathPatterns: Used to set the filtering rules that do not need to be intercepted
The interceptor is mainly Purpose: Intercept user login status, log interception, etc.
addCorsMappings cross-domain access
Crossing issues can also use crossing annotations and place them on the controller. @CrossOrigin(allowCredentials="true")
@Override
public void addCorsMappings(CorsRegistry registry) {
//允许所有请求跨越
registry.addMapping("/**");
//更加精准的跨越控制
registry.addMapping("/api/**")
.allowedOrigins("http://doain2.com")
.allowedMethods("POST","GET");
}
addViewControllers: page jump
When writing SpringMVC before, if you need to access a page, you must write the Controller class, and then write a method to jump to the page, which feels very troublesome. In fact, rewriting the addViewControllers method in WebMvcConfigurer can achieve the effect
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/toLogin").setViewName("login");
}
addResourceHandlers: static resources
For example, if we want to customize the static resource mapping directory, we only need to rewrite the addResourceHandlers method.
addResoureHandler: refers to the access path exposed to the outside world
addResourceLocations: refers to the directory where internal files are placed
/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
}
configureViewResolvers: view resolvers
This method is used to configure the view resolver. The parameter ViewResolverRegistry of this method is a register, which is used to register the view resolver you want to customize.
/**
* 配置请求视图映射
* @return
*/
@Bean
public InternalResourceViewResolver resourceViewResolver()
{
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//请求视图文件的前缀地址
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
//请求视图文件的后缀
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
/**
* 视图配置
* @param registry
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(resourceViewResolver());
}
configureMessageConverters: message converters
/**
* 消息内容转换配置
* 配置fastJson返回json转换
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//创建fastJson消息转换器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//修改配置返回内容的过滤
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
configureContentNegotiation: Configure some parameters for content arbitration
configureContentNegotiation(ContentNegotiationConfigurer configurer) This method is specially used to configure some parameters of content judgment. This is relatively simple, let's look directly at an example:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
/* 是否通过请求Url的扩展名来决定media type */
configurer.favorPathExtension(true)
/* 不检查Accept请求头 */
.ignoreAcceptHeader(true)
.parameterName("mediaType")
/* 设置默认的media yype */
.defaultContentType(MediaType.TEXT_HTML)
/* 请求以.html结尾的会被当成MediaType.TEXT_HTML*/
.mediaType("html", MediaType.TEXT_HTML)
/* 请求以.json结尾的会被当成MediaType.APPLICATION_JSON*/
.mediaType("json", MediaType.APPLICATION_JSON);
}