Springboot 2.x 请求参数之 @PathVariable 使用

一、@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;
    }
}

  

四、测试结果

 

posted @ 2021-01-17 17:24  变体精灵  阅读(1964)  评论(0编辑  收藏  举报