详解WebMvcConfigurer用法

2024-06-04 4656阅读

目录

一、路径匹配规则configurePathMatch

二、配置内容协商 configureContentNegotiation

三、配置异步请求的支持configureAsyncSupport  

四、配置格式化器addFormatters 

五、注册简单的视图控制器addViewControllers

六、注册自定义的参数解析器addArgumentResolvers

七、注册自定义的返回值处理器addReturnValueHandlers  

八、配置消息转换器configureMessageConverters  


WebMvcConfigurer 是 Spring Framework 中的一个接口,它提供了一种扩展 Spring MVC 配置的方式。通过实现 WebMvcConfigurer 接口,你可以定制化 Spring MVC 的配置,例如添加拦截器、资源处理、视图解析器等。

一、路径匹配规则configurePathMatch

configurePathMatch 是 WebMvcConfigurer 接口中的一个方法,它用于配置 Spring MVC 中的路径匹配规则。主要用于配置路径匹配的选项,例如设置路径是否区分大小写、路径后缀是否匹配等。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // 设置路径是否区分大小写,默认为 true
        configurer.setUseCaseSensitiveMatch(false);
        // 设置是否在路径匹配时忽略路径后缀,默认为 true
        configurer.setUseTrailingSlashMatch(true);
    }
}

在上述示例中,通过 configurePathMatch 方法设置了两个路径匹配的选项:

  1. setUseCaseSensitiveMatch(false):设置路径是否区分大小写。默认情况下,路径匹配是区分大小写的。如果设置为 false,则表示路径不区分大小写。

  2. setUseTrailingSlashMatch(true):设置是否在路径匹配时忽略路径后缀。默认情况下,路径匹配时会忽略路径后缀。如果设置为 true,则表示路径匹配时考虑路径后缀。

二、配置内容协商 configureContentNegotiation

configureContentNegotiation 是 WebMvcConfigurer 接口中的一个方法,它用于配置内容协商(Content Negotiation)的选项。内容协商是指客户端和服务器之间协商最适合的响应格式的过程。在 Spring MVC 中,可以通过 configureContentNegotiation 方法配置内容协商的相关选项。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        // 设置默认的内容类型
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
        // 启用路径扩展(例如:/data.json)
        configurer.favorPathExtension(true);
        // 启用参数扩展(例如:/data?format=json)
        configurer.favorParameter(true);
        // 设置参数名称,默认是 "format"
        configurer.parameterName("mediaType");
        // 设置支持的媒体类型
        configurer.mediaType("json", MediaType.APPLICATION_JSON);
        configurer.mediaType("xml", MediaType.APPLICATION_XML);
    }
}

在上述示例中,通过 configureContentNegotiation 方法设置了以下内容协商的选项:

  1. defaultContentType(MediaType.APPLICATION_JSON):设置默认的内容类型为 JSON。

  2. favorPathExtension(true):启用路径扩展,例如允许 /data.json 或 /data.xml。

  3. favorParameter(true):启用参数扩展,例如允许 /data?format=json 或 /data?format=xml。

  4. parameterName("mediaType"):设置参数名称,默认是 "format"。

  5. mediaType("json", MediaType.APPLICATION_JSON) 和 mediaType("xml", MediaType.APPLICATION_XML):设置支持的媒体类型。

三、配置异步请求的支持configureAsyncSupport  

configureAsyncSupport 是 WebMvcConfigurer 接口中的一个方法,它用于配置异步请求的支持。异步请求指的是客户端发起的请求,服务器在处理请求的过程中可以释放对连接的占用,而不必等待请求处理完成。这使得服务器能够更有效地处理大量的并发请求。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer.DefaultTimeoutConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        // 设置异步请求超时时间(毫秒)
        configurer.setDefaultTimeout(30000);
        // 设置异步请求线程池
        configurer.setTaskExecutor(myAsyncTaskExecutor());
        // 配置异步请求拦截器
        configurer.registerCallableInterceptors(myAsyncCallableInterceptor());
        configurer.registerDeferredResultInterceptors(myAsyncDeferredResultInterceptor());
    }
    // 自定义异步请求线程池
    @Bean
    public AsyncTaskExecutor myAsyncTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }
    // 自定义异步请求拦截器
    @Bean
    public CallableProcessingInterceptor myAsyncCallableInterceptor() {
        return new MyAsyncCallableInterceptor();
    }
    // 自定义DeferredResult拦截器
    @Bean
    public DeferredResultProcessingInterceptor myAsyncDeferredResultInterceptor() {
        return new MyAsyncDeferredResultInterceptor();
    }
    // 示例的自定义CallableProcessingInterceptor实现
    private static class MyAsyncCallableInterceptor implements CallableProcessingInterceptor {
        // 实现自定义逻辑
    }
    // 示例的自定义DeferredResultProcessingInterceptor实现
    private static class MyAsyncDeferredResultInterceptor implements DeferredResultProcessingInterceptor {
        // 实现自定义逻辑
    }
}

上述代码中,通过 configureAsyncSupport 方法配置了异步请求的一些选项:

  1. setDefaultTimeout(30000):设置异步请求的默认超时时间为 30 秒。

  2. setTaskExecutor(myAsyncTaskExecutor()):配置自定义的异步请求线程池。

  3. registerCallableInterceptors(myAsyncCallableInterceptor()):注册自定义的 Callable 请求拦截器。

  4. registerDeferredResultInterceptors(myAsyncDeferredResultInterceptor()):注册自定义的 DeferredResult 请求拦截器。

四、配置格式化器addFormatters 

addFormatters 是 WebMvcConfigurer 接口中的一个方法,用于配置格式化器(Formatter)。格式化器在 Spring MVC 中用于将字符串表示的数据转换成实际的 Java 对象,或者反过来将 Java 对象转换成字符串。

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 添加自定义的日期格式化器
        registry.addFormatter(new MyDateFormatter());
        // 添加自定义的金额格式化器
        registry.addFormatter(new MyCurrencyFormatter());
    }
    // 示例的自定义日期格式化器
    private static class MyDateFormatter implements Formatter {
        // 实现日期格式化逻辑
    }
    // 示例的自定义金额格式化器
    private static class MyCurrencyFormatter implements Formatter {
        // 实现金额格式化逻辑
    }
}

上述代码中,通过 addFormatters 方法配置了两个自定义的格式化器:

  1. MyDateFormatter:自定义的日期格式化器,实现了 Formatter 接口。

  2. MyCurrencyFormatter:自定义的金额格式化器,实现了 Formatter 接口。

五、配置拦截器addInterceptors 

addInterceptors 是 WebMvcConfigurer 接口中的一个方法,它用于配置拦截器(Interceptor)。拦截器可以用于在请求进入处理器(controller)之前或之后执行一些逻辑,例如日志记录、权限验证等。 

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加自定义的拦截器
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/public/**");
    }
    // 示例的自定义拦截器
    private static class MyInterceptor implements HandlerInterceptor {
        // 在请求处理之前调用
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // 实现拦截器的逻辑
            return true; // 继续执行后续的拦截器或处理器
        }
        // 在请求处理之后调用
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            // 实现拦截器的逻辑
        }
        // 在整个请求完成之后调用
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            // 实现拦截器的逻辑
        }
    }
}

上述代码中,通过 addInterceptors 方法配置了一个自定义的拦截器 MyInterceptor:

  • addPathPatterns("/api/**"):指定拦截的路径。

  • excludePathPatterns("/public/**"):指定不拦截的路径。

    MyInterceptor 类实现了 HandlerInterceptor 接口,其中的三个方法分别在请求处理之前、之后以及整个请求完成之后被调用。你可以在这些方法中实现自定义的拦截逻辑,例如权限验证、日志记录等。

    五、注册简单的视图控制器addViewControllers

    addViewControllers 是 WebMvcConfigurer 接口中的一个方法,用于注册简单的视图控制器,从而无需编写控制器方法即可实现 URL 到视图的映射。

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    @Configuration
    @EnableWebMvc
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            // 注册简单的视图控制器
            registry.addViewController("/home").setViewName("home");
            registry.addViewController("/login").setViewName("login");
            registry.addViewController("/dashboard").setViewName("dashboard");
        }
    }
    

    上述代码中,通过 addViewControllers 方法注册了三个简单的视图控制器:

    1. /home 映射到名为 "home" 的视图。
    2. /login 映射到名为 "login" 的视图。
    3. /dashboard 映射到名为 "dashboard" 的视图。

    六、注册自定义的参数解析器addArgumentResolvers


    addArgumentResolvers 是 WebMvcConfigurer 接口中的一个方法,用于注册自定义的参数解析器(Argument Resolvers)。参数解析器在 Spring MVC 中用于将请求中的参数映射到控制器方法的参数上,或者在处理器方法执行前进行一些额外的参数解析逻辑。 

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.List;
    @Configuration
    @EnableWebMvc
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
        @Override
        public void addArgumentResolvers(List argumentResolvers) {
            // 注册自定义的参数解析器
            argumentResolvers.add(new MyCustomArgumentResolver());
        }
        // 示例的自定义参数解析器
        private static class MyCustomArgumentResolver implements HandlerMethodArgumentResolver {
            // 实现参数解析逻辑
        }
    }
    

    上述代码中,通过 addArgumentResolvers 方法注册了一个自定义的参数解析器 MyCustomArgumentResolver。这个自定义的解析器需要实现 HandlerMethodArgumentResolver 接口,然后在接口方法中实现参数的解析逻辑。

    自定义参数解析器可以用于解析控制器方法的参数,将请求中的数据转换为控制器方法所需的参数类型。这样的定制可以用于处理一些特殊的场景,例如将请求中的 JSON 数据转换为对象等。

    七、注册自定义的返回值处理器addReturnValueHandlers  

    addReturnValueHandlers 是 WebMvcConfigurer 接口中的一个方法,用于注册自定义的返回值处理器(Return Value Handlers)。返回值处理器在 Spring MVC 中用于将控制器方法的返回值转换为响应体的内容。 

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.List;
    @Configuration
    @EnableWebMvc
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
        @Override
        public void addReturnValueHandlers(List returnValueHandlers) {
            // 注册自定义的返回值处理器
            returnValueHandlers.add(new MyCustomReturnValueHandler());
        }
        // 示例的自定义返回值处理器
        private static class MyCustomReturnValueHandler implements HandlerMethodReturnValueHandler {
            // 实现返回值处理逻辑
        }
    }
    

    上述代码中,通过 addReturnValueHandlers 方法注册了一个自定义的返回值处理器 MyCustomReturnValueHandler。这个自定义的处理器需要实现 HandlerMethodReturnValueHandler 接口,然后在接口方法中实现返回值的处理逻辑。

    自定义返回值处理器可以用于处理控制器方法的返回值,将其转换为适当的响应格式。这样的定制可以用于处理一些特殊的场景,例如将对象转换为 JSON 数据等。

    八、配置消息转换器configureMessageConverters  

    configureMessageConverters 是 WebMvcConfigurer 接口中的一个方法,用于配置消息转换器(Message Converters)。消息转换器在 Spring MVC 中负责将 HTTP 请求的数据转换为 Java 对象,以及将 Java 对象转换为 HTTP 响应的数据。

    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.List;
    @Configuration
    @EnableWebMvc
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
        @Override
        public void configureMessageConverters(List

    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]