矩阵变量指的是前端传递参数并不以问号?传递参数,
而是使用分号;传递参数
矩阵变量使用注意点
1)矩阵变量需要在springboot中手动开启,默认被springboot禁用了
2)根据规范,矩阵变量应该绑定在路径变量中,就是在路径中以;携带参数,/car/sell;xxx=xxx;...
3)若是有多个矩阵变量,应当使用;进行分割
4)若是一个矩阵变量有多个值,应当使用,进行分割,或者命名多个相同的key即可
5)想要使用矩阵变量,就得自己全权接收springmvc,无需springboot为我们注册springmvc各种组件,有三种方案
* 不用EnableWebMvc注解,使用@Configuration+WebMvcConfigurer
(是一个接口,接口方法有我们需要的各种组件)
* 声明WebMvcRegistrations改变默认底层组件
* 使用@EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration全面接管SpringMVC
小案例
前端页面
<a href="car/sell;price=20;brand=bm,bc,ym">测试矩阵变量</a>
后端控制器
@Controller
public class IndexController {
/*
@MatrixVariable获取路径变量中携带的price参数的值,如果有多个
路径变量且都带有相同的price参数,则使用pathVar属性获取指定的路径变量中的参数
本例子中只有一个路径变量。
*/
@ResponseBody
@RequestMapping("/car/{sell}")
public Map test1(@MatrixVariable(value = "price",pathVar = "sell")String price,
@MatrixVariable(value = "brand",pathVar = "sell") List<String> brands,
@PathVariable("sell")String path){
System.out.println(price);
System.out.println(brands);
System.out.println(path);
HashMap<String, Object> map = new HashMap<>();
map.put("price",price);
map.put("brands",brands);
map.put("path",path);
return map;
}
}
注册组件WebMvcConfigurer组件,配置自定义路径匹配,开启矩阵变量功能
@Component
public class MyConfig {
/*配置WebMvcConfigurer,定制化SpringMVC的功能*/
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
/*配置路径匹配,开启矩阵变量功能*/
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
//不移除;后面的内容,矩阵变量就可以生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
};
}
}
以上就是SpringBoot开启矩阵变量的全部配置。