@PathVariable是占位符注解。能够把Url中变量的值传递到方法参数中。
示例以下:app
@PostMapping("/user/name/{id}") @ResponseBody public User getUserName(@PathVariable("id") Integer id){ return userService.getUserNameById(id); }
当咱们输入的Url相似于 localhost:8080/user/name/1时,Controller层对应方法getUserName的参数id就会赋值为1。
可是要注意:
1.控制层的Url占位符{}中的变量,不要有多余的空格。
上述的代码,若是写多了几个空格,变成@PostMapping("/user/name/{ id }") ,就会有错误提示:post
Cannot resolve @PathVariable ' id '
2.postman请求的Url要写对,请求的Url中不用加{}。
若是Url不当心写成了 localhost:8080/user/name/{1},是没法正确访问的。只有相似 localhost:8080/user/name/1 才能够成功访问。code
这个注解很容易理解。主要仍是得细心一点。否则就可能会踩坑。get