版本spring4.x
註解@MatrixVariable可以將鍵值對寫到路徑中映射作爲controller中的方法參數,使用前需要配置
1.RequestMappingHandlerMapping中屬性removeSemicolonContent值爲true
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> <property name="order" value="1"></property> <property name="removeSemicolonContent" value="true"></property> </bean>
2.配置開啓
<mvc:annotation-driven enable-matrix-variables="true"/>
實例如下
// GET /m1/owners/42;q=11;r=12/pets/21;q=22;s=23 (官方示例有問題,此處無法找到)
// GET /m1/owners/q=11,12/pets/21;q=22;s=23
// (output matrixVars:{q=[11, 12, 22], s=[23]} petMatrixVars:{q=[22], s=[23]})
// 注意:如果/owners/***/pets/21;q=22;s=23中,***部分如果出現;(分號)就會找不到方法
@RequestMapping(value = "/m1/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public String findPet(@MatrixVariable Map<String, String> matrixVars,
@MatrixVariable(pathVar = "petId") Map<String, String> petMatrixVars) {
System.out.println(matrixVars+":matrixVars");
System.out.println(petMatrixVars+":petMatrixVars");
return "user_list";
}
// GET /pets/42;q=11;r=22 (output petId:42 q:11)
// GET /pets/q=11 (output petId:q=11 q:11)
@RequestMapping(value = "/m2/pets/{petId}", method = RequestMethod.GET)
public String findPet2(@PathVariable String petId, @MatrixVariable int q) {
System.out.println("petId:"+petId);
System.out.println("q:"+q);
return "user_list";
}
// GET /m3/owners/42;q=11/pets/21;q=22 (此處官方示例有點問題,這個路徑無法找到方法)
// GET /m3/owners/q=4/pets/q=21
@RequestMapping(value = "/m3/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public String findPet3(@MatrixVariable(value = "q", pathVar = "ownerId") int q1,
@MatrixVariable(value = "q", pathVar = "petId") int q2) {
System.out.println("q1:"+q1); // q1:4
System.out.println("q2:"+q2); // q2:21
return "user_list";
}
後來又測試了下removeSemicolonContent這個屬性可以不用配置,默認就是true