基本的请求方式介绍:
QueryString请求方式
/request?username=admin&age=20
Rest风格请求
/request/admin/123456/20
MatrixVariable矩阵变量
/request;username=admin;age=20
矩阵变量的含义:
根据 URI 规范 RFC 3986 中 URL 的定义,路径片段中可以包含键值对。规范中没有对应的术语…在 Spring MVC 它被成为矩阵变量。
使用方法:
由于SpringBoot中默认并没有开启矩阵变量的支持,直接关闭了矩阵变量。因此在使用的时候我们需要对SpringBoot自动装配的Bean对象进行手动的配置更改。
为了开启矩阵变量的使用必须实现WebMvcConfigurer接口,完成对configurePathMatch方法的手动实现并指定不移除分号后边的内容。
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper=new UrlPathHelper();
//不移除分号后面内容,使矩阵变量功能生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
在控制器中写一个方法,来接收矩阵变量并展示到页面之中,接收矩阵变量要用到路径变量 { } 进行占位:
//矩阵变量的获取
@ResponseBody
@GetMapping("/student/{path}")
public Map getMatrixVariable(@MatrixVariable("age") Integer age,
@MatrixVariable("name")List<String> name){
Map<String,Object> map=new HashMap<>();
map.put("age",age);
map.put("name",name);
return map;
}
页面中写一个超链接触发矩阵变量的请求:
<a th:href="@{/student/teacher;age=40;name=哈哈,呵呵}">获取矩阵变量的值</a>
效果:
若在一次请求中,请求中的矩阵变量相同如何取值呢?
模拟同名矩阵变量的请求:
<a th:href="@{/student/teacher;age=40/parent;age=45}">获取同名矩阵变量的值</a>
控制器方法:
//同名矩阵变量的获取
@ResponseBody
@GetMapping("/student/{path}/{path2}")
public Map getSameNameMatrixVariable(@MatrixVariable(value = "age",pathVar = "path") Integer age,
@MatrixVariable(value = "age",pathVar = "path2")Integer age2){
Map<String,Object> map=new HashMap<>();
map.put("teacherage",age);
map.put("parentage",age2);
return map;
}
效果: