In the previous article, we encountered the interface WebMvcConfigurer. Let’s take a look at some of these methods today.

Why use WebMvcConfigurer?

WebMvcConfigurer is an interface that provides a number of custom interceptors, such as cross domain Settings, type converters, and more. It can be said that this interface provides developers with a lot of interception requirements ahead of time, making it easy for developers to use it freely. Since Spring5.0 deprecated the WebMvcConfigurerAdapter, WebMvcConfigurer inherits most of the WebMvcConfigurerAdapter.

This section describes the WebMvcConfigurer method

Due to too much content, only 3 key interfaces are shown, with less use, just to illustrate the meaning, no longer detailed explanation, use even less, do not look at, after all, there are more than ten methods…

1.configurePathMatch(PathMatchConfigurer configurer)

This one is used less often, this one is related to the access path. For example, PathMatchConfigurer has a setUseTrailingSlashMatch() configuration. If set to true (the default is true), a slash does not affect path access. For example, “/user” equals “/user/”. We rarely mess around with access paths in development, so please do your own research on this approach if necessary.

2.configureContentNegotiation(ContentNegotiationConfigurer configurer)

This is called a content negotiation mechanism, which facilitates the return of multiple data formats in a single request path. You will see the MediaType ContentNegotiationConfigurer this configuration, there are many formats. This method will not be described in detail.

3.configureAsyncSupport(AsyncSupportConfigurer configurer)

As the name suggests, this handles asynchronous requests. Only two values can be set: timeout (milliseconds) and AsyncTaskExecutor, an asynchronous task executor.

4.configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)

This interface enables static files to be accessed like servlets.

5.addFormatters(FormatterRegistry registry)

Add a converter or formatter. Not only can you convert the time to the time zone or style you need. You can also customize the converter to interact with your database, such as passing in a userId that can be converted to retrieve a User object.

6.addInterceptors(InterceptorRegistry registry)

Looking forward to, looking forward to, you a commonly used method to come. This method allows you to customize the write interceptor and specify the interception path. Come on, let’s write an interceptor.

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        System.out.println("PreHandle, OK, let's say I give you true, run it.");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("PostHandle,ok, let's see when I run it.");
    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("AfterCompletion, OK, do you want to finish without a thumbs up?"); }}Copy the code

Then configure:

@Configuration
public class MyConfigurer implements WebMvcConfigurer {
    @Bean
    public MyInterceptor getMyInterceptor() {returnnew MyInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.getMyInterceptor())  .addPathPatterns("/abc"."/configurePathMatch"); }}Copy the code

You can see that addPathPatterns() allows you to try adding multiple paths, or write “/**”, including all paths that need to be tried and intercepted.

To test this, output:

PreHandle, OK, suppose I give you onetrueRun go === execute business logic === postHandle,ok, let's see when I run it. AfterCompletion,ok, afterCompletion?Copy the code

7.addResourceHandlers(ResourceHandlerRegistry registry)

Customize resource mappings. This is also commonly used in business scenarios where your own server acts as a file server and does not utilize a third-party graph bed, requiring a virtual path to map to the address of our server. It is worth mentioning that if your project is started with war package, it is generally configured in Tomcat (please refer to Baidu for the configuration method). You can use this method if you start from a JAR package, which is often the case with SpringBoot. Such as:

 public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/my/**")
    .addResourceLocations("file:E:/my/");
    super.addResourceHandlers(registry);
}
Copy the code

Real path, wndows In server case, must be preceded by a file:.

8.addCorsMappings(CorsRegistry registry)

This is to set up cross-domain issues, something that almost every backend server needs to configure. I wrote an article about cross-domain issues and how SpringBoot is configured: juejin.cn/post/684490…

9.addViewControllers(ViewControllerRegistry registry)

This method can be implemented by automatically jumping a path to a page. However, now most of the projects are separated from the front and back ends. Can we throw the problem of jump routing directly to the front end?

There are seven more to come: ConfigureViewResolvers, addArgumentResolvers, addReturnValueHandlers, configureMessageConverters, extendMessageConverters, co NfigureHandlerExceptionResolvers, extendHandlerExceptionResolvers. Is in the use of too little, no longer see.

summary

This article will give you a general idea of what these methods are, but most importantly WebMvcConfigurer has made some generic interceptors for our interception layer, so that developers can use them. You can also implement interceptors yourself. The most common ones are still 6, 7 and 8. The rest will be studied and updated later.