上篇我们学习了《45-Spring MVC的类型转换原理与配置2:
AnnotationFormatterFactory》,本篇我们学习Spring MVC的路径匹配和内容协商:PathMatchConfigurer。
3.9 路径匹配和内容协商
Spring MVC中可以通过重载WebMvcConfigurer接口的configurePathMatch方法来设置路径匹配。Spring MVC为我们提供了PathMatchConfigurer来进行路径匹配配置。
public void configurePathMatch(PathMatchConfigurer configurer) {
}
3.9.1 后缀匹配
使用PathMatchConfigurer.setUseSuffixPatternMatch(Boolean suffixPatternMatch)设置是否使用后缀匹配。若设置为true则路径/xx和/xx.*是等效的,Spring Boot下默认是false。
configurer.setUseSuffixPatternMatch(true);
我们还可以在外部配置application.yml快捷配置与同样的效果:
spring.mvc.pathmatch.use-suffix-pattern: true //Spring Boot默认是false
3.9.2 斜线匹配
使用PathMatchConfigurer.setUseTrailingSlashMatch(Boolean trailingSlashMatch)设置是否使用尾随斜线匹配。若设置为true,则路径/xx和/xx/等效,Spring MVC下默认是开启的,需关闭设置为false。
configurer.setUseTrailingSlashMatch(false);
截图演示的效果是默认情况下的效果:
3.9.3 路径前缀
可以通过PathMatchConfigurer.addPathPrefix(String prefix, Predicate
prefix设置路径的前缀,predicate设置匹配起效的控制器类型,本例为对@RestController有效:
configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));
3.9.4 内容协商
所谓“内容协商”指的是请求时使用不同的条件可获得不同的返回体的类型,如json,xml等。
在Spring Boot下我们可以在外部配置通过,实现根据“路径+.+扩展名”获得不同类型的返回体。
spring.mvc.contentnegotiation.favor-path-extension: true //偏好使用路径扩展名,如content.json
spring.mvc.pathmatch.use-registered-suffix-pattern: true //后缀只能是已注册扩展名,content.xx无效
Spring MVC已经为我们注册了媒体类型json;添加xml的支持jar到build.gradle。
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
}
我们用控制器验证:
@GetMapping("/content")
public AnotherPerson content(@RequestBody AnotherPerson person){
return person;
}
3.9.5 添加新的媒体类型
媒体类型的功能都是由HttpMessageConverter提供的,我们将我没钱前面注册的AnotherPersonHttpMessageConverter支持的媒体类型注册到内容协商。
我们可以通过重载WebMvcConfigurer接口的configureContentNegotiation方法,并使用Spring MVC提供的ContentNegotiationConfigurer来配置内容协商。
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("ap",
new MediaType("application","another-person", Charset.defaultCharset()));
}
或者通过外部配置来配置:
spring.mvc.contentnegotiation.media-types.ap: application/another-person
spring.mvc.contentnegotiation.media-types后支持一个Map类型,ap是key,application/another-person是MediaType类型的value。
我们访问
http://localhost:8080/people/content.ap,会使用
AnotherPersonHttpMessageConverter的处理来生成返回体。