详解WebMvcConfigurer用法

目录

一、路径匹配规则configurePathMatch

二、配置内容协商 configureContentNegotiation

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

四、配置格式化器addFormatters 

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

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

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

八、配置消息转换器configureMessageConverters  


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

一、路径匹配规则configurePathMatch

configurePathMatchWebMvcConfigurer 接口中的一个方法,它用于配置 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

configureContentNegotiationWebMvcConfigurer 接口中的一个方法,它用于配置内容协商(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  

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

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 

addFormattersWebMvcConfigurer 接口中的一个方法,用于配置格式化器(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<Date> {
        // 实现日期格式化逻辑
    }

    // 示例的自定义金额格式化器
    private static class MyCurrencyFormatter implements Formatter<BigDecimal> {
        // 实现金额格式化逻辑
    }
}

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

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

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

五、配置拦截器addInterceptors 

addInterceptorsWebMvcConfigurer 接口中的一个方法,它用于配置拦截器(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

addViewControllersWebMvcConfigurer 接口中的一个方法,用于注册简单的视图控制器,从而无需编写控制器方法即可实现 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


addArgumentResolversWebMvcConfigurer 接口中的一个方法,用于注册自定义的参数解析器(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<HandlerMethodArgumentResolver> argumentResolvers) {
        // 注册自定义的参数解析器
        argumentResolvers.add(new MyCustomArgumentResolver());
    }

    // 示例的自定义参数解析器
    private static class MyCustomArgumentResolver implements HandlerMethodArgumentResolver {
        // 实现参数解析逻辑
    }
}

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

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

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

addReturnValueHandlersWebMvcConfigurer 接口中的一个方法,用于注册自定义的返回值处理器(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<HandlerMethodReturnValueHandler> returnValueHandlers) {
        // 注册自定义的返回值处理器
        returnValueHandlers.add(new MyCustomReturnValueHandler());
    }

    // 示例的自定义返回值处理器
    private static class MyCustomReturnValueHandler implements HandlerMethodReturnValueHandler {
        // 实现返回值处理逻辑
    }
}

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

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

八、配置消息转换器configureMessageConverters  

configureMessageConvertersWebMvcConfigurer 接口中的一个方法,用于配置消息转换器(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<HttpMessageConverter<?>> converters) {
        // 注册自定义的消息转换器
        converters.add(new MyCustomMessageConverter());

        // 注册Jackson的JSON消息转换器
        converters.add(new MappingJackson2HttpMessageConverter());
    }

    // 示例的自定义消息转换器
    private static class MyCustomMessageConverter extends AbstractHttpMessageConverter<Object> {
        // 实现消息转换逻辑
    }
}

上述代码中,通过 configureMessageConverters 方法注册了两个消息转换器:

  1. MyCustomMessageConverter:自定义的消息转换器,需要继承 AbstractHttpMessageConverter 并实现相应的转换逻辑。

  2. MappingJackson2HttpMessageConverter:Jackson 框架提供的 JSON 消息转换器,用于将 JSON 数据转换为对象,以及将对象转换为 JSON 数据。

自定义消息转换器可以用于处理特殊的数据格式,例如 XML、Protocol Buffers 等。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

境里婆娑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值