SpringBoot提供的获取前端参数的注解,常用的有以下三个:
- @PathVariable
- @RequestParam
- @RequestBody
三者的区别如下表
1.Get请求的参数可以通过@PathVariable和@RequestParam获取
@GetMapping("/user/{id}")
public String getUser(@PathVariable(value = "id")Integer id,
@RequestParam(value = "name")String name,
@RequestParam(value = "sex",required = false,defaultValue = "0") Integer sex)
2.Post使用@RequestBody注解将Json格式的参数自动绑定到Entity类
@PostMapping("/user/check")
public String checkUser(@RequestBody User user)
3.Post使用@RequestParam获取请求体中非Json格式的数据
@PostMapping("/user/check")
public String checkUsers(@RequestParam("username") String username,
@RequestParam("password") String password)
4.Post请求也可以直接与对象类绑定,但需要参数名一致,不支持json格式,只支持form-data和x-www.form-urlencoded格式
@PostMapping("/user/add")
public String addUser(User user)