根據 URI 規范 RFC 3986 中 URL 的定義,路徑片段中可以可以包含鍵值對。規范中沒對對應的術語。一般 “URL 路徑參數” 可以被應用,盡管更加獨特的 “矩陣 URI” 也經常被使用並且相當有名。在 Spring MVC 它被成為矩陣變量
矩陣變量可以出現在任何路徑片段中,每一個矩陣變量都用分號(;)隔開。比如 “/cars;color=red;year=2012”。多個值可以用逗號隔開,比如 “color=red,green,blue”,或者分開寫 “color=red;color=green;color=blue”。
如果你希望一個 URL 包含矩陣變量,那么請求映射模式必須用 URI 模板來表示這些矩陣變量。這樣的話,不管矩陣變量順序如何,都能夠保證請求可以正確的匹配。
Springboot 默認是無法使用矩陣變量綁定參數的。需要覆蓋WebMvcConfigurer中的configurePathMatch方法。
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper=new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); } }
基於XML的配置
<mvc:annotation-driven enable-matrix-variables="true" />
編寫矩陣變量控制器
package com.techmap.examples.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.MatrixVariable; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/matrix") public class MatrixController { /** * 使用矩陣變量 */ @GetMapping("/owners/{ownerId}/pets/{petId}") public String findPet( @PathVariable String ownerId, @PathVariable String petId, @MatrixVariable(name = "q", pathVar = "ownerId") int q1, @MatrixVariable(name = "q", pathVar = "petId") int q2) { System.out.println("--> ownerId : " + ownerId); System.out.println("--> petId : " + petId); System.out.println("--> q1 : " + q1); System.out.println("--> q2 : " + q2); return "/examples/targets/test1"; } /** * 矩陣變量可以設置默認值 */ @GetMapping("/pets/{petId}") public String findPet( @MatrixVariable(required = false, defaultValue = "1") int q) { System.out.println("--> Default value of q : " + q); return "/examples/targets/test2"; } }
