@PathVariable只支持一个属性value,类型是为String,代表绑定的属性名称。默认不传递时,绑定为同名的形参。
用来便捷地提取URL中的动态参数。其英文注释如下:
Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for {@link RequestMapping} annotated handler methods in Servlet environments.
应用时,在@RequestMapping请求路径中,将需要传递的参数用花括号{}括起来,然后,通过@PathVariable("参数名称")获取URL中对应的参数值。如果@PathVariable标明参数名称,则参数名称必须和URL中参数名称一致。
@RequestMapping("/viewUser/{id}/{name}") public Map<String, Object> viewUser(@PathVariable("id") Integer idInt, @PathVariable Integer name) { System.out.println("@PathVariable中 请求参数 id = " + idInt); Map<String, Object> user = new HashMap<>(); user.put("id", idInt); user.put("name", name); return user; } /** * @Title viewUser2 * @Description @PathVariable未标注参数名称,则被注解参数名必须后URL中的一致 * @date 2018-12-15 11:08 */ @RequestMapping("/owners/{ownerId}") public Map<String, Object> viewUser2(@PathVariable Integer ownerId) { System.out.println("@PathVariable中 请求参数 ownerId = " + ownerId); Map<String, Object> user = new HashMap<>(); user.put("id", ownerId); user.put("name", "Lucy"); return user; }
URI 模板 “/owners/{ownerId}” 指定了一个名叫 ownerId的变量。当控制器处理这个请求时,ownerId的值被设置为从 URI 中解析出来。比如,当请求 /viewUser/100 进来时,100 就是 ownerId的值。