赞
踩
Spring MVC 接受参数的方式:
@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 }
// 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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。