@MatrixVariable 矩阵变量
语法:以; 号隔开 请求路径:/cars/sell;low=34;brand=byd,audi,yd
SpringBoot默认是禁用了矩阵变量的功能
手动开启:原理。对于路径的处理。UrlPathHelper的removeSemicolonContent设置为false,让其支持矩阵变量的。
矩阵变量必须有url路径变量才能被解析
手动开启矩阵变量:
实现WebMvcConfigurer接口:
@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
// 不移除;后面的内容。矩阵变量功能就可以生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
创建返回WebMvcConfigurerBean:
@Configuration(proxyBeanMethods = false)
public class WebConfig{
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
// 不移除;后面的内容。矩阵变量功能就可以生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
}
}
@MatrixVariable的用例
@RestController
public class ParameterTestController {
///cars/sell;low=34;brand=byd,audi,yd
@GetMapping("/cars/{path}")
public Map carsSell(@MatrixVariable("low") Integer low,
@MatrixVariable("brand") List<String> brand,
@PathVariable("path") String path){
Map<String,Object> map = new HashMap<>();
map.put("low",low);
map.put("brand",brand);
map.put("path",path);
return map;
}
// /boss/1;age=20/2;age=10
@GetMapping("/boss/{bossId}/{empId}")
public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
@MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
Map<String,Object> map = new HashMap<>();
map.put("bossAge",bossAge);
map.put("empAge",empAge);
return map;
}
}
UrlPathHelper
UrlPathHelper
这个帮助类非常的重要了,位于包org.springframework.web.util内。它帮助Spring MVC处理URL相关的各种难题,先介绍它的几个属性~~~
public class UrlPathHelper {
// 是否总是按照全路径 默认是false(一般不改~)
private boolean alwaysUseFullPath = false;
// 是否对url进行解码(默认都是需要解码的) 解码可以是request.getCharacterEncoding()。若没指定就是下面的defaultEncoding
private boolean urlDecode = true;
// 设置是否应从请求URI中删除“;”(分号)
private boolean removeSemicolonContent = true;
// 默认编码是它:ISO-8859-1
private String defaultEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
它
————————————————
引用链接:https://blog.csdn.net/f641385712/article/details/87814153