我正在阅读Spring 弹簧医生中的@Matrixvariable注释
我理解这个简单的语法// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET)
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
// petId == 42
// q == 11
}但是在理解下面的片段时有问题
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
@MatrixVariable Map<String, String> matrixVars,
@MatrixVariable(pathVar="petId"") Map<String, String> petMatrixVars) {
// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
// petMatrixVars: ["q" : 11, "s" : 23]
}这个语法@ Matrixvariable (pathVar=“petId”)是什么?我还没有理解Matrixvariable注释的pathVar属性?
这行对我来说没问题,// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23],这个变量添加了所有的矩阵变量。但是petMatrixVars是如何用这些特定的值添加的
//petMatrixVars: ["q" : 11, "s" : 23] ? why not //petMatrixVars: ["q" : 22, "s" : 23] ?提前感谢你花在这条线上的时间!!
发布于 2018-09-15 04:27:00
这称为Partial Binding,它用于获取路径中该段中的所有变量,或者如果您希望从路径段文档中获取每个变量,则输出在文档这里中是错误的。
在您的示例中,您将获得在petId {21}之后处于路径中的所有变量
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@MatrixVariable(pathVar="petId") Map<String, String> petMatrixVars)如果您只想在q段之后获得petId,那么
@MatrixVariable(value ="q",pathVar="petId") int q下面是输出的示例,对于@MatrixVariable,我们需要首先启用它们
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}使用@requestmapping方法的控制器
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
@MatrixVariable Map<String, String> matrixVars,
@MatrixVariable(pathVar="petId") Map<String, String> petMatrixVars) {
System.out.println(matrixVars);
System.out.println(petMatrixVars);
}
}请求:http://localhost:8080/sample/owners/42;q=11;r=12/pets/21;q=22;s=23
输出:
{q=11, r=12, s=23}
{q=22, s=23}如果我更改@MatrixVariable Map<String, List<String>> matrixVars,,输出是
{q=[11, 22], r=[12], s=[23]}
{q=22, s=23}https://stackoverflow.com/questions/52341438
复制相似问题