前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >@RequestParam、@RequestBody、@PathVariable区别和案例分析

@RequestParam、@RequestBody、@PathVariable区别和案例分析

作者头像
掉发的小王
发布2022-07-11 15:11:22
8100
发布2022-07-11 15:11:22
举报
文章被收录于专栏:小王知识分享小王知识分享

一、前言

@RequestParam、@RequestBody、@PathVariable都是用于在Controller层接收前端传递的数据,他们之间的使用场景不太一样,今天来介绍一下!!

二、实体类准备

代码语言:javascript
复制
@Data
public class Test implements Serializable {
  
    private String id;

    private String name;

    private String state;

    private String createTime;

}

三、@RequestParam

  • 定义

一个请求,可以有多个RequestParam @RequestParam 接收普通参数的注解 一般与get请求一起使用 @RequestParam(value="参数名",required="true/false",defaultValue="如果没有本值为这个参数的值") required默认为true,当为false是,才可以使用defaultValue

  • 案例
代码语言:javascript
复制
	@GetMapping("/getDataById")
    public String getDataById(@RequestParam(value = "id",required = false,defaultValue = "1") String id){

        //使用mybatis-plus来根据id查询数据
        Test test = testMapper.selectById(id);

        return test.toString();

        //结果: Test{id='1', name='dd', state='A', createTime='null'}
    }

四、@RequestBody

  • 定义

一个请求,只有一个RequestBody @RequestBody(required="true/false") @RequestBody:一般来接受请求体中json的注解 一般与post请求一起使用 required默认为true(比传,要不报错)

  • 案例
代码语言:javascript
复制
@PostMapping("/insertData")
    public int insertData(@RequestBody Test test){

        //使用mybatis-plus来插入新数据
        int insert = testMapper.insert(test);

        return insert;

        //结果: 1
    }

五、@PathVariable

  • 定义

一个请求,可以有多个PathVariable @PathVariable 映射URL绑定的占位符 一般与get请求一起使用 @PathVariable(value="参数名",required="true/false")

  • 案例
代码语言:javascript
复制
	@GetMapping("/getById/{id}")
    public String getById(@PathVariable String id){
        //使用mybatis-plus来根据id查询数据
        Test test = testMapper.selectById(id);

        return test.toString();

        //结果: Test{id='1', name='dd', state='A', createTime='null'}
    }

六、区别和使用场景

@RequestParam一般在get请求时,参数是一个个的参数时,请求url一般为http://localhost:8089/test/getDataById?id=1 @RequestBody一般在post请求时,参数是一个对象或者集合时,请求一般为json类型的请求体 @PathVariable一般在get请求时,参数是一个个的参数时,更能体现RestFul风格,请求url一般为:http://localhost:8089/test/getDataById/1

Q.E.D.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-01-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、前言
  • 二、实体类准备
  • 三、@RequestParam
  • 四、@RequestBody
  • 五、@PathVariable
  • 六、区别和使用场景
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档