@RequestParam和@PathVariable的区别和使用

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

@PathVariable

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

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

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

@RequestMapping("testl/fid}/fname}")
public String testPathVariable(@PathVariable String id, @PathVariable string name)
return "id=" + id +",name="+ name;

@Pathvariable 支持下面三种参数:

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

@RequestParam

主要用于接收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,reguired这三个参数,而ReguestParam也有这三个参数,并且比PathVariable多一个参数defaultValue(该参数用于当请求体中不包含对应的参数变量时,参数变量使用defaultValue指定的默认值)
  • 3.PathVariable一般用于get和delete请求,RequestParam一般用于post请求。
@RestController
public class TestController {

    @RequestMapping("test1/fid}/{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;
    }

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值