Spring MVC 中接受参数的方式

Spring MVC 接受参数的方式:

  1. 无注解方式
  2. @RequestParam 方式:参数绑定
  3. @PathVariable 方式:url 匹配
  4. @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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值