从WebMvcConfigurer接口看SpringMVC为我们提供了哪些功能

Posted 敲代码的小小酥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从WebMvcConfigurer接口看SpringMVC为我们提供了哪些功能相关的知识,希望对你有一定的参考价值。

前言

在SpringBoot中,通常采用零配置SpringMVC。如果我们想自定义一些配置,可以通过实现WebMvcConfigurer接口完成。下面,我们就根据这个接口,来了解SpringMVC为我们提供了哪些可配置的选项。

应用

我们结合源码,来看SpringMVC都有哪些配置项。
**

configurePathMatch:

**

/**
	 * Helps with configuring HandlerMappings path matching options such as trailing slash match,
	 * suffix registration, path matcher and path helper.
	 * Configured path matcher and path helper instances are shared for:
	 * <ul>
	 * <li>RequestMappings</li>
	 * <li>ViewControllerMappings</li>
	 * <li>ResourcesMappings</li>
	 * </ul>
	 * @since 4.0.3
	 */
	default void configurePathMatch(PathMatchConfigurer configurer) {
	}

该方法可以人为改变request的url和handler的映射关系。一般的,我们都是通过@Requestmapping注解来定义映射,这种定义的方式,是静态的。而这个方法可以动态的定义或改变映射关系,下面我们看如下代码:

 public void configurePathMatch(PathMatchConfigurer configurer) {
                // 是否存在尾\\来进行匹配  /user和/user/等效的,同样可以进行匹配
                configurer.setUseTrailingSlashMatch(true);

                // 这个配置需要传入一个UrlPathHelper对象,UrlPathHelper是一个处理url地址的帮助类,
                // 他里面有一些优化url的方法
                // 比如:getSanitizedPath,就是将// 换成/  所以我们在输入地址栏的时候,//也是没有问题的,
                // 这里使用springmvc默认的就可以了,如果想要深入了解,那么我们后续在深入
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                configurer.setUrlPathHelper(urlPathHelper);

                // 路径匹配器 PathMatcher是一个接口,springmvc默认使用的是AntPathMatcher
                // 这里也就不深入了,使用springmvc默认的就可以,如果想要深入了解,那么我们后续在深入,查看AntPathMatcher的源码
                // configurer.setPathMatcher();

                // 配置路径前缀
                // 下面这样写的意思是:对含有AdminController注解的controller添加/admin地址前缀
                configurer.addPathPrefix("admin", c -> c.isAnnotationPresent(AdminController.class));
                configurer.addPathPrefix("app", c -> c.isAnnotationPresent(AppController.class));
                // 当然这里也不一定非得用注解来实现:也可以用分包:
                // configurer.addPathPrefix("app", c -> c.getPackage().getName().contains("com.osy.controller.admin"));
                // configurer.addPathPrefix("app", c -> c.getPackage().getName().contains("com.osy.controller.app"));

            }

可以看到,我们可以自定义修改映射关系,使请求到达不同的handler。

configureContentNegotiation内容协商机制

内容协商机制的意思就是客户端需要服务端返回什么样的数据格式(如json还说xml),客户端可以指定。通过configureContentNegotiation方法定义协商机制。

 public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                // 是否通过请求参数来决定返回数据,默认为false
                configurer.favorParameter(true)
                        .ignoreAcceptHeader(true) // 不检查Accept请求头
                        .parameterName("zyMediaType")// 参数名称,就是通过什么样的参数来获取返回值
                        .defaultContentType(MediaType.APPLICATION_JSON)
                        .mediaType("json",MediaType.APPLICATION_JSON)
                        .mediaType("xml",MediaType.APPLICATION_XML);
                        // mediaType此方法是从请求参数扩展名(也就是最后一个.后面的值),
                        // 然后绑定在parameterName上面,比如/admin/getUser.xml  等同于/admin/getUser?zyMediaType=xml
                        // 如果不需要这种后缀的,那么就是全部通过参数的方式传递到后台

            }

addInterceptors

自定义添加一些拦截器,这是常规操作,不过多讲解,直接上代码:

public void addInterceptors(InterceptorRegistry registry) {
            // addInterceptor方法是注册一个生命周期拦截器,addPathPatterns方法是拦截的url地址,
            // excludePathPatterns是排除那些地址不拦截,order方法是拦截顺序,就是拦截器执行链的执行顺序,值越大,拦截就越靠后,这里注册两个是为了验证顺序的
                registry.addInterceptor(new ZyInterceptor()).addPathPatterns("/**").excludePathPatterns("/test").order(1);
                registry.addInterceptor(new OtherInterceptor()).addPathPatterns("/**").excludePathPatterns("/test").order(2);
            }

addResourceHandlers

这个比较常用,配置静态资源与请求地址映射,使得springmvc不对其进行拦截,并且能够快速找到。

 public void addResourceHandlers(ResourceHandlerRegistry registry) {
            	// 添加静态资源路径,然后跟项目的路径进行映射
                registry.addResourceHandler("/static/**","/**").addResourceLocations("classpath:/static/");
            }

addCorsMappings

跨域配置,也很常用:

public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**") // 添加请求映射,就是对哪些地址进行跨域处理
                        .allowedOrigins("*") // 特定来源的允许来源列表。这里配置*表示所以网站都可进行跨域,这里生产介意指定特定的地址
                        .allowedHeaders("*") // 允许请求头携带的标题: "Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"
                        .allowCredentials(true) // 浏览器是否携带凭证
                        .allowedMethods("*") // 允许跨域的请求方式,可以进行指定:GET,POST
                        .maxAge(3600); // 客户端缓存的时间,默认为1800(30分钟)
            }

addViewControllers

SpringMVC根据配置自动生成Controller。用于返回统一界面等没有逻辑的Controller。可以通过此方法进行配置。

public void addViewControllers(ViewControllerRegistry registry) {
            	// 这里前提得有404和500这一个html存在,不然他会返回他默认的404页面
                registry.addViewController("/404").setStatusCode(HttpStatus.NOT_FOUND).setViewName("404");
                registry.addViewController("/500").setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR).setViewName("500");
            }

addFormatters

增加转化器或者格式化器。这边不仅可以把时间转化成你需要时区或者样式。还可以自定义转化器和你数据库做交互,比如传进来userId,经过转化可以拿到user对象。

以上是关于从WebMvcConfigurer接口看SpringMVC为我们提供了哪些功能的主要内容,如果未能解决你的问题,请参考以下文章

Springboot 实现WebMvcConfigurer接口来拓展SpringMvc的功能

WebMvcConfigurer详解

spring设计好美:WebMvcConfigurer

SpringBoot WebMvcConfigurer详解

详解Springboot中自定义SpringMVC配置

springboot 中的commandLineRunners接口