Spring MVC 接受参数的方式:
- 无注解方式
- @RequestParam 方式:参数绑定
- @PathVariable 方式:url 匹配
- @RequestBody 方式:请求对象 → \to → JSON
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
}
@RestController
public class ParamController {
//无注解方式
@GetMapping("noAnnotation")
public User noAnnotation(User user) {
return user;
}
// @RequestParams 方式:url上的参数与方法上参数绑定
@GetMapping("/requestParam")
public User requestParams(@RequestParam String name, @RequestParam int age) {
return new User(name, age);
}
// @PathVariable 方式:获取 url 上的路径
@GetMapping("/pathVariable/{name}/{age}")
public User pathVariable(@PathVariable String name, @PathVariable int age) {
return new User(name, age);
}
// @RequestBody 方式:对象 -> JSON
@PostMapping("/requestBody")
public User requestBody(@RequestBody User user) {
System.out.println("user = " + user);
return user;
}
}
使用 HTTP Request 请求
### 无注解方式
GET http://localhost:8080/noAnnotation?name=foo&age=20
Accept: application/json
### @RequestParams 方式
GET http://localhost:8080/requestParam?name=foo&age=20
Accept: application/json
### @PathVariable 方式
GET http://localhost:8080/pathVariable/foo/20
Accept: application/json
### @RequestBody 方式
POST http://localhost:8080/requestBody
Content-Type: application/json
{
"name": "foo",
"age": 20
}
添加 value 的作用: 参数转换
// name -> qwe
@GetMapping("/requestParam2")
public User requestParams2(@RequestParam(value = "qwe") String name, @RequestParam int age) {
return new User(name, age);
}
// name -> qwe
@GetMapping("/pathVariable2/{qwe}/{age}")
public User pathVariable2(@PathVariable(value = "qwe") String name, @PathVariable int age) {
return new User(name, age);
}
### @RequestParams2 方式
GET http://localhost:8080/requestParam2?qwe=foo&age=20
Accept: application/json
### @PathVariable2 方式
GET http://localhost:8080/pathVariable2/qwe/20
Accept: application/json