SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
来源:互联网 发布:潍坊知行学校 编辑:程序博客网 时间:2024/06/08 03:33
SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
本篇博文将介绍几种如何处理url中的参数的注解@PathVaribale/@RequestParam/@GetMapping。
其中,各注解的作用为:
@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写
@PathVaribale 获取url中的数据
看一个例子,如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
同样,如果我们需要在url有多个参数需要获取,则如下代码所示来做就可以了。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
以上,通过@PathVariable注解来获取URL中的参数时的前提条件是我们知道url的格式时怎么样的。
只有知道url的格式,我们才能在指定的方法上通过相同的格式获取相应位置的参数值。
一般情况下,url的格式为:localhost:8080/hello?id=98,这种情况下该如何来获取其id值呢,这就需要借助于@RequestParam来完成了
@RequestParam 获取请求参数的值
直接看一个例子,如下
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
在浏览器中输入地址:localhost:8080/hello?id=1000,可以看到如下的结果:
当我们在浏览器中输入地址:localhost:8080/hello?id ,即不输入id的具体值,此时返回的结果为null。具体测试结果如下:
但是,当我们在浏览器中输入地址:localhost:8080/hello ,即不输入id参数,则会报如下错误:
@RequestParam注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值,具体代码如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
测试结果如下;
如果在url中有多个参数,即类似于localhost:8080/hello?id=98&&name=wojiushimogui这样的url,同样可以这样来处理。具体代码如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
在浏览器中的测试结果如下:
@GetMapping 组合注解
@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。
即可以使用@GetMapping(value = “/hello”)来代替@RequestMapping(value=”/hello”,method= RequestMethod.GET)。即可以让我们精简代码。
例子
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
小结
本篇博文介绍了几种常用获取url中的参数哈,比较简单。
- SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
- SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
- SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
- SpringBoot中常用注解@ PathVaribale / @ RequestParam / @ GetMapping介绍 本篇博文将介绍几种如何处理URL中的参数的注解@ PathVariba
- SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍
- SpringBoot中常用的注解
- springboot 一些常用的注解介绍
- springboot 常用注解
- springboot常用注解二
- 常用springboot注解
- springboot常用注解总结
- SpringBoot常用注解
- SpringBoot常用注解
- SpringBoot常用注解
- Springboot 常用注解
- 【SpringBoot】常用注解
- Springboot 常用注解
- SpringBoot一些常用注解
- 手机不root也能看数据库
- Ubuntu刚使用时的问题
- 如何在kernel中得到cpu的电压和频率
- 关于Fragment的IllegalStateException的部分经验
- Android编译和运行原理学习笔记
- SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
- 遗传算法理论与实现
- 【番外篇·C】函数
- jquery表格插件——Datables的浅显学习
- sas 9.4 64 win10 sid
- node-工作模型及错误处理
- 你知道PORT吗?
- 压缩代码和资源
- js模块化编程之彻底弄懂CommonJS和AMD/CMD