一、@PathVariable 作用
使用該注解可以獲取 URI 中的路徑變量值,可以獲取單個,也可以使用 Map<String,String> 來獲取所有的路徑變量的 name 和 value
二、@PathVariable 注解聲明
// 可以使用 @PathVariable 獲取 URI 中的單個路徑變量
/**
* Annotation which indicates that a method parameter should be bound to a URI template
* variable. Supported for {@link RequestMapping} annotated handler methods.
*
*/
// 如果使用 Map<String,String> 作為形式參數,那么該 Map 將封裝所有的路徑變量的 name 和 value
/**
* <p>If the method parameter is {@link java.util.Map Map<String, String>}
* then the map is populated with all path variable names and values.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see RequestMapping
* @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
// name 和 value 互為別名
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the path variable to bind to.
* @since 4.3.3
*/
@AliasFor("value")
String name() default "";
// required 屬性,默認值是 true ,也就是如果形參中指定了某一個屬性,那么發送的請求中必須攜帶該路徑變量值,否則會拋出異常,
// 例如 @PathVariable("userId") Integer id ,那么你的請求路徑中必須要攜帶一個 userId 參數,否則拋出異常
/**
* Whether the path variable is required.
* <p>Defaults to {@code true}, leading to an exception being thrown if the path
* variable is missing in the incoming request. Switch this to {@code false} if
* you prefer a {@code null} or Java 8 {@code java.util.Optional} in this case.
* e.g. on a {@code ModelAttribute} method which serves for different requests.
* @since 4.3.3
*/
boolean required() default true;
}
三、@PathVariable 使用
@RestController
public class RequestParamsController {
@GetMapping("/user/{userId}/games/{favGames}")
public Map userInfo(
// 獲取路徑變量中 userId 的值,並將其賦值給形參的 id 變量
@PathVariable("userId") Integer id,
// 獲取路徑變量中 favGames 的值,並將其賦值給形參的 games 變量
@PathVariable("favGames") String games,
// 獲取所有的形參變量,也就是{} 中變量對應的值,使用 Map<String,String> 進行封裝
@PathVariable Map<String,String> pathParams) {
Map map = new HashMap<String, Object>();
map.put("id", id);
map.put("games", games);
map.put("pathParams", pathParams);
return map;
}
}
四、測試結果