最近学习看一些代码,发现对于发送请求这件事,有的地方用@RequestMapping,有的地方用@PostMapping,为了搞清楚区别,特意查了下spring 源代码,现在特此记录下。
@GetMapping 用于将HTTP get请求映射到特定处理程序的方法注解
- 具体来说,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
@PostMapping 用于将HTTP post请求映射到特定处理程序的方法注解
- 具体来说,@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。
下面我们来看下@GetMapping的源码
可以对上面的两句释义给予充分的支撑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /**
* Annotation for mapping HTTP {@code GET} requests onto specific handler
* methods.
*
* <p>Specifically, {@code @GetMapping} is a <em>composed annotation</em> that
* acts as a shortcut for {@code @RequestMapping(method = RequestMethod.GET)}.
*
*
* @author Sam Brannen
* @since 4.3
* @see PostMapping
* @see PutMapping
* @see DeleteMapping
* @see PatchMapping
* @see RequestMapping
*/
@Target (ElementType.METHOD)
@Retention (RetentionPolicy.RUNTIME)
@Documented
@RequestMapping (method = RequestMethod.GET)
public @interface GetMapping {
/**
* Alias for {@link RequestMapping#name}.
*/
@AliasFor (annotation = RequestMapping. class )
String name() default "" ;
...
}
|
上面代码中,最关键的是
1 | @RequestMapping (method = RequestMethod.GET)
|
这行代码即说明@GetMapping就是@RequestMapping附加了请求方法。
同时,可以看到@GetMapping这个注解 是spring4.3版本引入,同时引入的还有@PostMapping、@PutMapping、@DeleteMapping和@PatchMapping,一共5个注解。
所以,一般情况下用
1 | @RequestMapping (method = RequestMethod. XXXX)
|
即可。
SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
介绍几种如何处理url中的参数的注解@PathVaribale/@RequestParam/@GetMapping。
其中,各注解的作用为:
@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写
看一个例子,如果我们需要获取Url=localhost:80/consumer/get/{id}中的返回的dept值,实现代码如下:

以上,通过@PathVariable注解来获取URL中的时参数的前提条件是我们知道url的格式时怎么样的。
只有知道url的格式,我们才能在指定的方法上通过相同的格式获取相应位置的参数值。
一般情况下,url的格式为:localhost:80/consumer/get/{id},这种情况下该如何来获取其中的返回的dept值呢,
关于@RequestParam来完成获取返回值代码如下

当输入:http://localhost/consumer/dept/get/1?id=1
看到返回了dept的结果:

但是当输入:http://localhost/consumer/dept/get/1 (即不输入id参数和参数值)
但是当输入:http://localhost/consumer/dept/get/1?id (不输入id参数值)
会报如下错误:

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

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

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

@GetMapping 组合注解
@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。
即可以使用@GetMapping(value = “/dept/get/{id}”)来代替
1 | @RequestMapping (value=”/dept/get/{id}”,method= RequestMethod.GET)
|
即可以让我们精简代码。

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

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

小结
本篇文章介绍了几种常用获取url中的参数哈,比较简单。以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
|