当前位置: 首页 > news >正文

@RequestMapping 和 @GetMapping等子注解的区别及其用法

常用的请求映射注解介绍

  1. @GetMapping
    • 用于处理 HTTP GET 请求。
    • 等价于 @RequestMapping(method = RequestMethod.GET)
    1@GetMapping("/path")
    2public String handleGetRequest() {
    3    return "GET request handled";
    4}
  2. @PostMapping
    • 用于处理 HTTP POST 请求。
    • 等价于 @RequestMapping(method = RequestMethod.POST)
    1@PostMapping("/path")
    2public String handlePostRequest(@RequestBody String data) {
    3    return "POST request handled";
    4}
  3. @PutMapping
    • 用于处理 HTTP PUT 请求。
    • 等价于 @RequestMapping(method = RequestMethod.PUT)
    1@PutMapping("/path")
    2public String handlePutRequest(@RequestBody String data) {
    3    return "PUT request handled";
    4}
  4. @DeleteMapping
    • 用于处理 HTTP DELETE 请求。
    • 等价于 @RequestMapping(method = RequestMethod.DELETE)
    1@DeleteMapping("/path")
    2public String handleDeleteRequest() {
    3    return "DELETE request handled";
    4}
  5. @PatchMapping
    • 用于处理 HTTP PATCH 请求。
    • 等价于 @RequestMapping(method = RequestMethod.PATCH)
    1@PatchMapping("/path")
    2public String handlePatchRequest(@RequestBody String data) {
    3    return "PATCH request handled";
    4}
  6. @OptionsMapping
    • 用于处理 HTTP OPTIONS 请求。
    • 等价于 @RequestMapping(method = RequestMethod.OPTIONS)
    1@OptionsMapping("/path")
    2public String handleOptionsRequest() {
    3    return "OPTIONS request handled";
    4}
  7. @HeadMapping
    • 用于处理 HTTP HEAD 请求。
    • 等价于 @RequestMapping(method = RequestMethod.HEAD)
    1@HeadMapping("/path")
    2public String handleHeadRequest() {
    3    return "HEAD request handled";
    4}
  8. @RequestMapping
    • 用于映射 HTTP 请求。
    • 可以指定多个 HTTP 方法。
1@RequestMapping(value = "/path", method = {RequestMethod.GET, RequestMethod.POST})
2public String handleMultipleRequests(@RequestParam String param) {
3    return "Multiple requests handled";
4}


区别及其用法

详细解释一下 @RequestMapping@GetMapping 等子注解的区别及其用法。

注:一下以@GetMapping 为例,其他子注解同理

 @RequestMapping 注解

@RequestMapping 是一个通用的请求映射注解,它可以用来映射 HTTP 请求到特定的方法。它可以单独使用或者与其他注解(如 @GetMapping@PostMapping 等)结合使用。

@RequestMapping 的用法:
  • 路径映射:指定请求的 URL 路径。
  • HTTP 方法:可以指定一个或多个 HTTP 方法(如 GET、POST、PUT、DELETE 等)。
示例代码:
1@RequestMapping("/test")
2public class TestController {
3
4    @RequestMapping(method = RequestMethod.GET)
5    public String handleGetRequest() {
6        return "GET request handled";
7    }
8
9    @RequestMapping(method = RequestMethod.POST)
10    public String handlePostRequest() {
11        return "POST request handled";
12    }
13}


 @GetMapping 注解

@GetMapping 是一个方便的注解,专门用来映射 HTTP GET 请求。它是 @RequestMapping 的子注解,内部使用 @RequestMapping(method = RequestMethod.GET) 实现。

@GetMapping 的用法:
  • 仅用于 GET 请求:专门用来处理 HTTP GET 请求。
示例代码:
1@GetMapping("/test")
2public String handleGetRequest() {
3    return "GET request handled";
4}

组合使用

@RequestMapping 可以与 @GetMapping@PostMapping 等注解组合使用,以实现更细粒度的请求映射。

示例代码:
1@Controller
2@RequestMapping("/test")
3public class TestController {
4
5    @GetMapping
6    public String handleGetRequest() {
7        return "GET request handled";
8    }
9
10    @PostMapping
11    public String handlePostRequest() {
12        return "POST request handled";
13    }
14}

总结

  • @RequestMapping:是一个通用的请求映射注解,可以映射各种 HTTP 方法(GET、POST、PUT、DELETE 等)。
  • @GetMapping:专门用于处理 GET 请求,简化了代码。

使用建议

  • 如果一个方法只处理 GET 请求,使用 @GetMapping 更加简洁明了。
  • 如果一个方法需要处理多种 HTTP 方法,使用 @RequestMapping 并指定方法类型。


示例代码汇总

以下是完整的示例代码:

后端代码
1package com.example.demo;
2
3import org.springframework.web.bind.annotation.*;
4
5@RestController
6@RequestMapping("/test")
7public class TestController {
8
9    @GetMapping
10    public String handleGetRequest(@RequestParam String username) {
11        System.out.println("已接收到请求" + username);
12        return "传输成功";
13    }
14
15    @PostMapping
16    public String handlePostRequest(@RequestBody String data) {
17        System.out.println("已接收到 POST 数据:" + data);
18        return "POST 数据处理成功";
19    }
20}
前端代码
1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>表单提交数据</title>
7</head>
8<body>
9
10    <!-- GET 请求 -->
11    <form action="http://localhost:8080/test" method="get">
12        <input type="text" name="username">
13        <input type="submit" value="提交 GET 请求">
14    </form>
15
16    <!-- POST 请求 -->
17    <button onclick="sendPostRequest()">提交 POST 请求</button>
18
19    <script>
20        function sendPostRequest() {
21            fetch('http://localhost:8080/test', {
22                method: 'POST',
23                headers: {
24                    'Content-Type': 'application/json'
25                },
26                body: JSON.stringify({ data: 'Hello, POST!' })
27            })
28            .then(response => response.text())
29            .then(data => console.log(data))
30            .catch(error => console.error('Error:', error));
31        }
32    </script>
33    
34</body>
35</html>

希望通过上述代码,你可以清楚地区分 GET 请求和 POST 请求,并且了解如何使用 @RequestMapping@GetMapping 注解来处理不同类型的请求。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • UAC2.0 麦克风——双声道 USB 麦克风(16bit)
  • 阿里云盘惊现“一锅端“的 Bug,我刚充的钱啊!
  • C++笔记---继承(上)
  • 香港电讯SASE解决方案:终端与云端的安全护航
  • FloodFill(洪水灌溉)算法专题——DFS深搜篇
  • 【C#生态园】选择最适合你的工具:C# GUI库完整比较及指南
  • C++第二讲:类和对象
  • 从入门到精通,玩转Python的print函数(探索Python print函数的隐藏功能)
  • 实时数仓3.0DWD层
  • kali里面搭建docker容器
  • leetcode 难度【简单模式】标签【数据库】题型整理大全
  • 小红书热门系列,风口副业项目AI宠物壁纸号,玩法分享
  • Go语言入门实战教程(超详细)从零基础入门到高级实战,看完就懂了(2024年新版,建议收藏)
  • Python 课程15-PyTorch
  • 产品探秘|开物——面向AI原生和云原生网络研究的首选科研平台
  • 网络传输文件的问题
  • Promise面试题,控制异步流程
  • Python_网络编程
  • Python学习笔记 字符串拼接
  • RedisSerializer之JdkSerializationRedisSerializer分析
  • swift基础之_对象 实例方法 对象方法。
  • uni-app项目数字滚动
  • 开发了一款写作软件(OSX,Windows),附带Electron开发指南
  • 线上 python http server profile 实践
  • 学习笔记:对象,原型和继承(1)
  • 追踪解析 FutureTask 源码
  • ​学习一下,什么是预包装食品?​
  • ‌前端列表展示1000条大量数据时,后端通常需要进行一定的处理。‌
  • #ifdef 的技巧用法
  • #if和#ifdef区别
  • (10)工业界推荐系统-小红书推荐场景及内部实践【排序模型的特征】
  • (13)[Xamarin.Android] 不同分辨率下的图片使用概论
  • (2)(2.10) LTM telemetry
  • (DFS + 剪枝)【洛谷P1731】 [NOI1999] 生日蛋糕
  • (二)pulsar安装在独立的docker中,python测试
  • (算法)硬币问题
  • (原創) 如何使用ISO C++讀寫BMP圖檔? (C/C++) (Image Processing)
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • (最完美)小米手机6X的Usb调试模式在哪里打开的流程
  • ***检测工具之RKHunter AIDE
  • *算法训练(leetcode)第四十五天 | 101. 孤岛的总面积、102. 沉没孤岛、103. 水流问题、104. 建造最大岛屿
  • .gitattributes 文件
  • .NET 6 Mysql Canal (CDC 增量同步,捕获变更数据) 案例版
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .NET 中什么样的类是可使用 await 异步等待的?
  • .NET框架
  • .NET使用存储过程实现对数据库的增删改查
  • .xml 下拉列表_RecyclerView嵌套recyclerview实现二级下拉列表,包含自定义IOS对话框...
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • @JoinTable会自动删除关联表的数据
  • @ModelAttribute使用详解
  • @基于大模型的旅游路线推荐方案
  • [ 环境搭建篇 ] 安装 java 环境并配置环境变量(附 JDK1.8 安装包)
  • [AIGC] SQL中的数据添加和操作:数据类型介绍
  • [C++] 轻熟类和对象