首页 技术 正文
技术 2022年11月6日
0 收藏 418 点赞 442 浏览 1531 个字

一、前言

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

二、实体类准备

@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

  • 案例
@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(必传,要不报错)

  • 案例
@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”)

  • 案例
@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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,489
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,290