@RequestParam,@PathVariable和@RequestBody

@RequestParam 和 @PathVariable 注解是用于从request中接收请求的,两个都可以接收参数,关键点不同的是@RequestParam 是从request里面拿取值,而 @PathVariable 是从一个URI模板里面来填充

@PathVariable(用于获取Restful风格的路径参数)

主要用于接收http://host:port/path/{参数值}数据:

http://localhost:8887/test1/id1/name1

根据上面的这个url,你可以用这样的方式来进行获取:

@PostMapping("test1/{id}/{name}")
public String testPathVariable(@PathVariable String id, @PathVariable String name) {
    return "id=" + id + ", name=" + name;
}

@PathVariable支持下面三种参数:

  • name 绑定本次参数的名称,要跟URL上面的一样
  • required 这个参数是否必须的
  • value 跟name一样的作用,是name属性的一个别名

@RequestParam(用于获取QueryString风格的参数)

主要用于接收http://host:port/path?参数名=参数值数据,这里后面也可以不跟参数值;

http://localhost:8887/test2?id=id2&name=name2

根据上面的这个url,你可以用这样的方式来进行获取:

 @RequestMapping("test2")
    public String testRequestParam(@RequestParam("id") String id, @RequestParam("name") String name) {
        return "id=" + id + ", name=" + name;
    }

@RequestParam 支持下面四种参数:

  • defaultValue 如果本次请求没有携带这个参数,或者参数为空,那么就会启用默认值
  • name 绑定本次参数的名称,要跟URL上面的一样
  • required 这个参数是否必须的
  • value 跟name一样的作用,是name属性的一个别名

@PathVariable和@RequestParam混合使用

http://localhost:8887/test3/id3?name=name3

根据上面的这个url,你可以用这样的方式来进行获取:

@RequestMapping("test3/{id}")
public String test3(@PathVariable String id, @RequestParam("name") String name) {
    return "id=" + id + ", name=" + name;
}

对比
1.用法上的不同:
PathVariable只能用于接收url路径上的参数,而RequestParam只能用于接收请求带的params
2.内部参数不同:
PathVariable有value,name,required这三个参数,而RequestParam也有这三个参数,并且比PathVariable多一个参数defaultValue(该参数用于当请求体中不包含对应的参数变量时,参数变量使用defaultValue指定的默认值)
3.PathVariable一般用于get和delete请求,RequestParam一般用于post请求。
代码

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Author: hmm
 * @Date: 2021/7/20
 */
@RestController
public class TestController {

    @RequestMapping("test1/{id}/{name}")
    public String testPathVariable(@PathVariable String id, @PathVariable String name) {
        return "id=" + id + ", name=" + name;
    }


    @RequestMapping("test2")
    public String testRequestParam(@RequestParam("id") String id, @RequestParam("name") String name) {
        return "id=" + id + ", name=" + name;
    }

    @RequestMapping("test3/{id}")
    public String test3(@PathVariable String id, @RequestParam("name") String name) {
        return "id=" + id + ", name=" + name;
    }
}

@RequestBody(用于获取请求体中json格式的参数)

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值