首页 > 其他分享 >@RequestMapping 和 @GetMapping等子注解的区别及其用法

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

时间:2024-09-18 13:53:50浏览次数:3  
标签:HTTP RequestMapping GET 等子 GetMapping return String

常用的请求映射注解介绍

  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 注解来处理不同类型的请求。

标签:HTTP,RequestMapping,GET,等子,GetMapping,return,String
From: https://blog.csdn.net/Yluciud/article/details/142330967

相关文章

  • java: 错误: 无效的源发行版:17解决方法、java: 无法访问org.springframework.web.bind
    可能的问题与解决方法java:错误:无效的源发行版:17(18)解决方法遇到这种问题大概率是版本以及配置出现问题,可以试试看按下面的步骤排除检查先检查自己的Java版本去到项目结构看Java配置是否正确这里以我的Java1.8举例主要是修改SDK为正确对应检查依赖项是否正确(i......
  • @RequestMapping注解有哪些属性?
    在SpringFramework中,@RequestMapping注解用于将HTTP请求映射到MVC和REST控制器的处理方法上。它是SpringMVC中最基本的注解之一,可以应用在类级别或方法级别。@RequestMapping注解拥有多个属性,以下是其中的一些常用属性及其解释:value/path:类型:String[]描......
  • SpringMVC:@RequestMapping注解
    1.@RequestMapping作用@RequestMapping`注解是SpringMVC框架中的一个控制器映射注解,用于将请求映射到相应的处理方法上。具体来说,它可以将指定URL的请求绑定到一个特定的方法或类上,从而实现对请求的处理和响应。2. 出现位置的区别出现在类上//@RequestMapping注......
  • 【Spring】SpringMVC中@RequestMapping 详解
    1、简介在SpringMVC中,@RequestMapping是一个非常重要的注解,它用于映射web请求(如HTTP请求)到特定的处理器方法或处理器类。2、基本用法@RequestMapping可以标注在方法或类上。当标注在类上时,它提供了初步的请求映射信息,如请求路径的前缀。当标注在方法上时,它提供了具体的......
  • SpringMVC(1)-@RequestMapping的简单使用
    本文核心内容来自于韩顺平老师的课程@RequestMapping注解可以用来指定控制器或者处理器的某个方法的请求url@ControllerpublicclassUserServlet{@RequestMapping("/login")publicStringlogin(){return"login";}}1@RequestMappi......
  • Java解决最长相邻不相等子序列I
    Java解决最长相邻不相等子序列I01题目给你一个下标从0开始的字符串数组words,和一个下标从0开始的二进制数组groups,两个数组长度都是n。你需要从words中选出最长子序列。如果对于序列中的任何两个连续串,二进制数组groups中它们的对应元素不同,则word......
  • 关于SpringMVC中@RequestMapping的params参数
    @RequestMapping注解的params参数同一个url,只要params不同,springmvc也是会区分匹配的。@PostMapping("/reduceProductStock")publicStringreduceProductStock(@RequestParamLongproductId,@RequestParamIntegerquantity){productService.reduceProductStock(pr......
  • SpringBoot:通过实现自定义接口获取实现类的@RequestMapping注解请求路径
    1.自定义接口//什么都不用写,就定义一个空接口publicinterfaceMyMark{}2.Controller接口类实现自定义接口@RestControllerpublicclassDayControllerimplementsMyMark{@RequestMapping("/day1")publicStringget1(){return"day1";}......
  • 9.springMvc中函数的返回值是什么 10.springmvc中@RequestMapping注解都有那些属性
    springMvc的返回值可以有很多类型,如String,modleAndView等,但事一般使用String比较友好。 在SpringMVC中,`@RequestMapping`注解用于将请求映射到控制器的处理方法。它可以应用在类级别和方法级别上,用于处理不同的URL请求。以下是`@RequestMapping`注解的一些常见用......
  • springMVC的常见注解,以及注解的作用。@Controller,@RestController,@RequestMapping,@
    目录注:使用注解,必须要开启注解包扫描1.@Controller2.@RequestMapping3.@PathVariable4.@RequestParam5.@RequestHeader6.@CookieValue7.@RequestBody该注解的作用8.@ResponseBody9.@RestController注:使用注解,必须要开启注解包扫描在MVC核心配置中开启注解包扫描<!--  配置包......