SpringBoot中的@PathVariable注解 @RequestParam注解 @RequestBody注解 超级详细用法

注解支持的类型支持的请求类型支持的Content-Type请求示例
@PathVariableurlGET所有/test/{id}
@RequestParamurlGET或POST所有/test?id=1或{“id”:1}
@RequestBodyBodyPOST/PUT/DELETE/PATCHjson{“id”:1}

1、@PathVariable 一般用于GET请求

url: http://127.0.0.1:8099/test/10?name=xiaohong

    @GetMapping("/test/{id}")
    public Object test(@PathVariable Long id,@RequestParam("name") String name){
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "成功");
        return map;
    }

2、@RequestParam 一般用于GET请求或者POST请求

GET请求
url: http://127.0.0.1:8099/test?id=10&cid=123456

@GetMapping("/test")
public Object test(@RequestParam String param,@RequestParam("cid") String cid){
      Map<String, Object> map = new HashMap<>();
      map.put("code", 200);
      map.put("msg", "成功");
      return map;
}

POST请求
url: http://127.0.0.1:8099/test
特别注意!!!
微信小程序uniapp中请求的时候需要设置请求头!如果不设置的话默认是application/json,这个时候就不能用@RequestParam获取了只能用@requestBody Map param获取。
设置成application/x-www-form-urlencoded就可以用@RequestParam获取里面的参数了!

uni或wx.request({
	url: getApp().globalData.myurl + '/register',
	data: {
		phone: this.phone,
		email: this.email,
		password: this.password,
	},
	method: 'POST',
	dataType: 'json',
	header:{
		//设置请求头!不设置的话默认就是application/json
		'content-type': 'application/x-www-form-urlencoded'
	},
	success(res){
		
	},

请求头为application/json使用以下方式:

@PostMapping("/test")
public Object test(@RequestParam Map<String,String> map){
    int id = map.get("id")
    int cid = map.get("cid")
    System.out.print(id +" "+ cid)
    Map<String, Object> map = new HashMap<>();
    map.put("code", 200);
    map.put("msg", "成功");
    return map;
}

请求头为application/x-www-form-urlencoded使用以下方式:

@GetMapping("/test")
public Object test(@RequestParam String param,@RequestParam("cid") String cid){
    Map<String, Object> map = new HashMap<>();
    map.put("code", 200);
    map.put("msg", "成功");
    return map;
}

3、@RequestBody 一般用于实体类来接收数据

默认请求头为application/json
使用@RequestBody前端request发请求的时候就不用设置请求头了!使用默认的application/json

@PostMapping("/add")
public Object add(@RequestBody User user) {
    Map<String, Object> map = new HashMap<>();
    map.put("code", 200);
    map.put("msg", "成功");
    return map;
}
// user是我们的实体类
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

令人作呕的溏心蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值