聊聊@RequestMapping和@GetMapping @PostMapping的区别

2022-10-18,,,

这篇文章主要介绍了@RequestMapping和@GetMapping及@PostMapping的区别,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

@RequestMapping和@GetMapping @PostMapping的区别

最近学习看一些代码,发现对于发送请求这件事,有的地方用@RequestMapping,有的地方用@PostMapping,为了搞清楚区别,特意查了下spring 源代码,现在特此记录下。

  • @GetMapping用于将HTTP get请求映射到特定处理程序的方法注解
  • 具体来说,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
  • @PostMapping用于将HTTP post请求映射到特定处理程序的方法注解
  • 具体来说,@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

下面我们来看下@GetMapping的源码

可以对上面的两句释义给予充分的支撑。

/**
 * 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 ""; 
    ... 
}

上面代码中,最关键的是

@RequestMapping(method = RequestMethod.GET)

这行代码即说明@GetMapping就是@RequestMapping附加了请求方法。

同时,可以看到@GetMapping这个注解 是spring4.3版本引入,同时引入的还有@PostMapping、@PutMapping、@DeleteMapping和@PatchMapping,一共5个注解。

所以,一般情况下用

@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}”)来代替

@RequestMapping(value=”/dept/get/{id}”,method= RequestMethod.GET)

即可以让我们精简代码。

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

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

小结

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

您可能感兴趣的文章:

  • springboot中Getmapping获取参数的实现方式
  • 关于@GetMapping和@GetMapping(value=““)的区别
  • 基于@GetMapping注解携带参数的方式

《聊聊@RequestMapping和@GetMapping @PostMapping的区别.doc》

下载本文的Word格式文档,以方便收藏与打印。