小工具知识网

当前位置: 首页 > 行业知识 > 详解WebMvcConfigurer用法

行业知识

详解WebMvcConfigurer用法

2026-11-02 17:55:14 来源:互联网转载

目录

一、路径匹配规则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;@Configurationpublic 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;@Configurationpublic 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;@Configurationpublic 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@EnableWebMvcpublic 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@EnableWebMvcpublic 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@EnableWebMvcpublic 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@EnableWebMvcpublic 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@EnableWebMvcpublic 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@EnableWebMvcpublic class MyWebMvcConfigurer implements WebMvcConfigurer {    @Override    public void configureMessageConverters(List

上一篇:麻雀算法SSA,优化VMD,适应度函数为最小包络熵,包含MATLAB源代码

下一篇:爸妈怎么标声调?