当前位置:网站首页>@pathvariable 和 @Requestparam的详细区别
@pathvariable 和 @Requestparam的详细区别
2022-07-07 00:41:00 【码农研究僧】
前言
使用springboot项目的时候,经常看到这两个注解的在项目中的混用
对于springboot的基础知识点可看我之前的文章:
springboot从入门到精通(全)
今天详细分析下@pathvariable 和 @Requestparam(都归属spring注解)
- @PathVariable:/manongyanjiuseng/18
- @RequestParam:/manongyanjiuseng?age=18
区别在于一个是用?,一个使用/进行传输数据
这种格式类似:RESTFul从入门到精通超全解析(全)

1. 源码解析
查看@pathvariable注解的源码:
@Target({
ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
boolean required() default true;
}
查看@Requestparam注解的源码:
@Target({
ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
boolean required() default true;
String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}
对比两者的源码
@Requestparam 比 @pathvariable多了一个参数String defaultValue()
大致意思:如果请求体中没有对应的参数变量,使用default对该参数变量赋值,赋上默认值
@pathvariable 和 @Requestparam 这两个注解一般配合如下注解进行联动:
@GetMapping、@PostMapping 和 @RequestMapping详细区别附实战代码(全)
总的来说:
@pathvariable 接收url路径上的参数
@RequestParam 接收参数请求的params
对于源码中的其他参数讲解:
- @Target 作用于参数中
- @Retention作用是定义被它所注解的注解保留多久,RetentionPolicy.RUNTIME注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
- @Documented,生成javadoc的时候就会把@Documented注解给显示出来,但其实也没啥用处,一个标识而已
2. 实战讲解
以上两个注解都要配合请求体的参数
@PathVariable 注解
@GetMapping ("/manongyanjiuseng/{age}")
@ResponseBody
public String xx( @PathVariable ( "age" ) String age)
@Requestparam注解
@RGetMapping ("/manongyanjiuseng")
@ResponseBody
public String xx( @RequestParam ( "age" ) String age)
具体的传参如下:
- @PathVariable:/manongyanjiuseng/18
- @RequestParam:/manongyanjiuseng?age=18
边栏推荐
- Mysql-centos7 install MySQL through yum
- 数字IC面试总结(大厂面试经验分享)
- STM32按键状态机2——状态简化与增加长按功能
- Input of native applet switches between text and password types
- What is message queuing?
- CTFshow--常用姿势
- PowerPivot - DAX (function)
- yarn入门(一篇就够了)
- Three level menu data implementation, nested three-level menu data
- Modes of optical fiber - single mode and multimode
猜你喜欢
随机推荐
产业金融3.0:“疏通血管”的金融科技
SAP ABAP BDC(批量数据通信)-018
老板总问我进展,是不信任我吗?(你觉得呢)
TCC of distributed transaction solutions
SQL Server 2008 各种DateTime的取值范围
Things about data storage 2
What EDA companies are there in China?
async / await
驱动开发中platform设备驱动架构详解
架构设计的五个核心要素
Mybaits multi table query (joint query, nested query)
Three level menu data implementation, nested three-level menu data
Harmonyos practice - Introduction to development, analysis of atomized services
SAP webservice 测试出现404 Not found Service cannot be reached
原生小程序 之 input切换 text与password类型
On the difference between FPGA and ASIC
什么是消息队列?
zabbix_ Get test database failed
R语言【逻辑控制】【数学运算】
How to improve website weight









