SpringBoot series --WebMvcConfigurer Introduction

In the last article, we encountered the interface WebMvcConfigurer. Probably today to see what methods have inside it.

Why use WebMvcConfigurer?

WebMvcConfigurer is an interface that provides a number of custom interceptor, arranged cross-domain e.g., the type of converter and the like. This interface can be said for the developer needs a lot of thought in advance to intercept level, enabling developers to easily use freedom of choice. Since Spring5.0 abandoned WebMvcConfigurerAdapter, so WebMvcConfigurer WebMvcConfigurerAdapter inherited most of the contents.

WebMvcConfigurer method described

Since the content too much, just to show three key interface with the relatively small, but the meaning set forth under, no longer explain, with less, do not read, more than a dozen methods after all it ...

1.configurePathMatch (PathMatchConfigurer configure)

The use of relatively small, and this is related to the access path. For example, there is a configuration example PathMatchConfigurer is setUseTrailingSlashMatch (), if it is set to true (the default is true), plus a back slash path does not affect access, such as "/ user" is equivalent to "/ user /". We rarely do things on the access path in development, so this method if need your own research it.

2.configureContentNegotiation (ContentNegotiationConfigurer configure)

The literal translation of what is called content negotiation, mainly to facilitate a return path request multiple data formats. ContentNegotiationConfigurer this configuration Inside you will see MediaType, there are a number of formats. This method is not more than repeat them.

3.configureAsyncSupport (AsyncSupportConfigurer configure)

As the name suggests, this is a processing asynchronous requests. Only two set values, a timeout (default ms, the Tomcat 10,000 milliseconds, i.e., 10 seconds), there is a AsyncTaskExecutor, an asynchronous tasks.

4.configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)

This interface can be implemented as static files can be accessed as Servlet.

5.addFormatters(FormatterRegistry registry)

Or a formatter increase conversion. Not only here can you need to put time into time zones or style. You can also customize the conversion and you do interact with the database, such as passed in userId, after conversion can get user object.

6.addInterceptors(InterceptorRegistry registry)

Looking forward, looking forward, you come a commonly used method. This method can write custom interceptors, and specify the path to intercept. Come, let's write a blocker.

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle,ok,假设给你一个true,运行去吧");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle,ok,看看我什么时候运行的。");
    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion,ok,看完不点个赞再走吗?");
    }
}

Then configure the look:

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

It can be seen addPathPatterns () which can try to add multiple paths, or written as "/ *", contains all paths need to try to intercept it.

Test, output:

preHandle,ok,假设给你一个true,运行去吧
===》执行业务逻辑===》
postHandle,ok,看看我什么时候运行的。
afterCompletion,ok,看完不点个赞再走吗?

7.addResourceHandlers(ResourceHandlerRegistry registry)

Custom resource mapping. This thing is also more commonly used business scenario is their server as a file server, does not use third-party view of the bed, you need a virtual path is mapped to the address of our server. It is worth mentioning that, if your project is to start war package, usually re-configure Tomcat look (configuration information, Baidu); if it is jar package starts (SpringBoot often start this way), you can use this way to go. E.g:

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

The true path, wndows when the server's front must add a file :.

8.addCorsMappings(CorsRegistry registry)

This is to set the cross-domain problem, almost every thing you need to configure the backend server. I wrote an article devoted to cross-domain issues and SpringBoot how to configure, query:
https://juejin.im/post/5cfe6367f265da1b9163887f

9.addViewControllers(ViewControllerRegistry registry)

This method can be implemented, a path automatically jump to a page. But now mostly separated before and after the end of the project, the route is not possible to jump directly to throw the front of the problem.

And there are seven: configureViewResolvers, addArgumentResolvers, addReturnValueHandlers, configureMessageConverters, extendMessageConverters, configureHandlerExceptionResolvers, extendHandlerExceptionResolvers. Is using too little, I no longer read.

summary

Benpian probably know at first what are these methods, the most important thing is for us to know WebMvcConfigurer another interception layer made some general interceptor, enabling developers to easily use. Of course, you can implement your own interceptor. The most commonly used is or 6,7,8. Others have the opportunity to study good and then update.

Guess you like

Origin www.cnblogs.com/pjjlt/p/11005811.html