SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

释放双眼,带上耳机,听听看~!

本篇博文将介绍几种如何处理url中的参数的注解@PathVaribale/@RequestParam/@GetMapping。

其中,各注解的作用为:

@PathVaribale 获取url中的数据

@RequestParam 获取请求参数的值

@GetMapping 组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写

看一个例子,如果我们需要获取Url=localhost:80/consumer/get/{id}中的返回的dept值,实现代码如下:

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

以上,通过@PathVariable注解来获取URL中的时参数的前提条件是我们知道url的格式时怎么样的。

只有知道url的格式,我们才能在指定的方法上通过相同的格式获取相应位置的参数值。

一般情况下,url的格式为:localhost:80/consumer/get/{id},这种情况下该如何来获取其中的返回的dept值呢,

 

关于@RequestParam来完成获取返回值代码如下

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

 

当输入:http://localhost/consumer/dept/get/1?id=1

看到返回了dept的结果:

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

 

但是当输入:http://localhost/consumer/dept/get/1      (即不输入id参数和参数值)

但是当输入:http://localhost/consumer/dept/get/1?id    (不输入id参数值)

会报如下错误:

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

 

 

@RequestParam注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值,具体代码如下:

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

此时输入:http://localhost/consumer/dept/get/1?id        就不在报错(使用了默认值)

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

输入:http://localhost/consumer/dept/get/1

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

 

 

@GetMapping 组合注解

@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。

即可以使用@GetMapping(value = “/dept/get/{id}”)来代替@RequestMapping(value=”/dept/get/{id}”,method= RequestMethod.GET)。即可以让我们精简代码。

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

输入:http://localhost/consumer/dept/get/1?id

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

 

输入:http://localhost/consumer/dept/get/1

SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

小结

本篇博文介绍了几种常用获取url中的参数哈,比较简单。如果喜欢请关注我博客

 

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++异常

2022-1-11 12:36:11

安全技术

golang 安装

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索