1. Introduction

The WebMvcConfigurer class is an internal configuration method in Spring. It uses javabeans instead of XML configuration files to customize the framework. You can customize some handlers, Interceptor, ViewResolver, etc. MessageConverter. The Java-based Spring MVC configuration needs to create a configuration class and implement the WebMvcConfigurer interface.

In Spring Boot 1.5, the WebMvcConfigurerAdapter method was overridden to add custom interceptors, message converters, and so on. After SpringBoot 2.0, this class is marked @deprecated. Official recommended directly implement WebMvcConfigurer or directly inherit WebMvcConfigurationSupport, interface (recommended), a realization WebMvcConfigurer way two WebMvcConfigurationSupport class inheritance.

2. WebMvcConfigurer interface

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(); }Copy the code

Common methods:

Void addInterceptors(InterceptorRegistry var1); Void addViewControllers(ViewControllerRegistry registry); /** * static resource handler **/ void addResourceHandlers(ResourceHandlerRegistry registry); / * default static processor resources/void configureDefaultServletHandling (DefaultServletHandlerConfigurer configurer); /** */ void configureViewResolvers(ViewResolverRegistry registry); / * configuration options * / void content's decision configureContentNegotiation (ContentNegotiationConfigurer configurer); **/ public void addCorsMappings(CorsRegistry registry);Copy the code

2.1 addInterceptors: Interceptors

  • AddInterceptor: You need an interceptor instance that implements the HandlerInterceptor interface
  • AddPathPatterns: Used to set filtering path rules for interceptors;addPathPatterns("/**")All requests are intercepted
  • ExcludePathPatterns: Used to set up filtering rules that do not need to be blocked
  • The interceptor is mainly used to intercept user login status and logs.
@Override public void addInterceptors(InterceptorRegistry registry) { super.addInterceptors(registry); registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**").excludePathPatterns("/emp/toLogin","/emp/login","/js/**","/css/**","/images/** "); }Copy the code

2.2 addViewControllers: Page jump

In the old days of SpringMVC, if you wanted to access a page, you had to write the Controller class, and then write a method to jump to the page, which felt like a hassle. Instead, you could override the addViewControllers method in WebMvcConfigurer

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");
    }
Copy the code

Value indicates that overriding the addViewControllers method here does not override the addViewControllers in WebMvcAutoConfiguration (Springboot automatic configuration). Spring Boot maps “/” to index.html), which means that both your own configuration and Spring Boot’s automatic configuration are valid, which is how we recommend adding our own MVC configuration.

 

2.3 addResourceHandlers: Static resources

For example, if we want to customize the static resource mapping directory, we simply override the addResourceHandlers method.

Note: if the inheritance WebMvcConfigurationSupport class implements configuration must override this method.

@ Configuration public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer {/ configure static access to the resource * * * * @ param registry * / @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/"); }}Copy the code
  • AddResoureHandler: Indicates the exposed access path
  • AddResourceLocations: Indicates the directory where the internal files are placed

2.4 configureDefaultServletHandling: static processor resources by default

@Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable();  configurer.enable("defaultServletName"); }Copy the code

At this time will be registered a Handler: the default DefaultServletHttpRequestHandler, the Handler is used to deal with static files, it will attempt to map /. When DispatcherServelt mapping/(/ and/there is a difference between), and to find a suitable Handler to handle the request, will be handed over to DefaultServletHttpRequestHandler to deal with. Note: Static resources are placed in the Web root directory, not web-INF. Maybe the description here is a bit confusing (I feel the same way myself), so here’s a quick example: In the Webroot directory there is an image: 1.png We know that files in the webroot directory (Webroot) can be accessed directly in the servlet specification, but because DispatcherServlet is configured with the mapping path: /, it almost all the requests are blocked, leading to a PNG can’t access, then register a DefaultServletHttpRequestHandler can solve this problem. Actually can be understood as a DispatcherServlet destroyed a feature of the Servlet (files can direct access to the root directory), DefaultServletHttpRequestHandler is to help to return to this feature.

 

2.5 configureViewResolvers: View resolvers

This method is used to configure the view resolver. The argument to ViewResolverRegistry is a registry used to register the view resolver you want to customize, etc.

/ * * * configuration request view map * @ return * / @ Bean public InternalResourceViewResolver resourceViewResolver () { InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); / / request view file prefix address internalResourceViewResolver. Methods setPrefix ("/WEB - INF/JSP/"); / / request view file suffix internalResourceViewResolver setSuffix (". The JSP "); return internalResourceViewResolver; } @override public void configureViewResolvers(ViewResolverRegistry registry) { super.configureViewResolvers(registry); registry.viewResolver(resourceViewResolver()); /*registry.jsp("/WEB-INF/jsp/",".jsp"); * /}Copy the code

2.6 configureContentNegotiation: ruling configuration content of some parameters

2.7 addCorsMappings: Cross-domain

@Override
public void addCorsMappings(CorsRegistry registry) {
    super.addCorsMappings(registry);
    registry.addMapping("/cors/**")
            .allowedHeaders("*")
            .allowedMethods("POST","GET")
            .allowedOrigins("*");
}
Copy the code

2.8 configureMessageConverters: information converter

/** * Message content conversion configuration * fastJson Return JSON conversion * @param converters */ @override public void configureMessageConverters(List<HttpMessageConverter<? > > converters) {/ / call the superclass configuration super configureMessageConverters (converters); / / create fastJson message converter FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter (); FastJsonConfig = new FastJsonConfig(); / / modify configuration returns the content filtering fastJsonConfig setSerializerFeatures (SerializerFeature DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty ); fastConverter.setFastJsonConfig(fastJsonConfig); // Add fastJSON to the view message converter list converters.add(fastConverter); }Copy the code