Spring Boot中的RESTful API详细介绍及使用

在Spring Boot中,RESTful API的实现通过控制器类中的方法和特定的注解来完成。每个注解对应不同的HTTP请求方法,并通过处理请求参数和返回响应来实现不同的操作。

下面将详细解释RESTful API中的各个方面,包括@GetMapping, @PostMapping, @PutMapping, 和 @DeleteMapping的作用及区别、请求参数和返回参数。

作用及区别

  1. @GetMapping:

    • 作用: 处理HTTP GET请求,用于获取资源。通常用于读取数据,不应更改服务器上的资源。
    • 区别: 是幂等的,多次请求相同资源不会改变服务器状态。
    • 示例:
      @GetMapping("/users")
      public List<User> getAllUsers() {
          // 获取所有用户
      }
      
      @GetMapping("/users/{id}")
      public User getUserById(@PathVariable Long id) {
          // 获取指定ID的用户
      }
      
  2. @PostMapping:

    • 作用: 处理HTTP POST请求,用于创建新资源。通常用于提交数据,服务器会创建新的资源。
    • 区别: 不是幂等的,多次请求会创建多个资源。
    • 示例:
      @PostMapping("/users")
      public User createUser(@RequestBody User user) {
          // 创建新用户
      }
      
  3. @PutMapping:

    • 作用: 处理HTTP PUT请求,用于更新资源。通常用于更新现有资源的全部内容。
    • 区别: 是幂等的,多次请求相同资源会导致相同的更新结果。
    • 示例:
      @PutMapping("/users/{id}")
      public User updateUser(@PathVariable Long id, @RequestBody User user) {
          // 更新指定ID的用户
      }
      
  4. @DeleteMapping:

    • 作用: 处理HTTP DELETE请求,用于删除资源。通常用于删除服务器上的资源。
    • 区别: 是幂等的,多次请求相同资源删除操作只会导致资源被删除一次。
    • 示例:
      @DeleteMapping("/users/{id}")
      public void deleteUser(@PathVariable Long id) {
          // 删除指定ID的用户
      }
      

请求参数

  1. @RequestBody:

    • 作用: 将请求体中的JSON数据绑定到方法参数上。
    • 使用场景: 常用于@PostMapping@PutMapping
    • 示例:
      @PostMapping("/users")
      public User createUser(@RequestBody User user) {
          // 请求体中的JSON数据将绑定到user对象
      }
      
  2. @PathVariable:

    • 作用: 将URL路径中的变量绑定到方法参数上。
    • 使用场景: 常用于@GetMapping, @PutMapping, 和 @DeleteMapping
    • 示例:
      @GetMapping("/users/{id}")
      public User getUserById(@PathVariable Long id) {
          // URL中的id将绑定到方法参数id
      }
      
  3. @RequestParam:

    • 作用: 将查询参数绑定到方法参数上。
    • 使用场景: 适用于各种HTTP方法。
    • 示例:
      @GetMapping("/users")
      public List<User> getUsersByAge(@RequestParam int age) {
          // URL中的查询参数age将绑定到方法参数age
      }
      

返回参数

  1. 返回对象:

    • 作用: 方法可以直接返回对象,Spring Boot会自动将其转换为JSON格式。
    • 示例:
      @GetMapping("/users/{id}")
      public User getUserById(@PathVariable Long id) {
          // 返回User对象,自动转换为JSON
      }
      
  2. ResponseEntity:

    • 作用: 可以自定义HTTP响应状态码、响应头和响应体。
    • 示例:
      @PostMapping("/users")
      public ResponseEntity<User> createUser(@RequestBody User user) {
          User createdUser = userService.createUser(user);
          return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
      }
      

综合示例

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping
    public List<User> getAllUsers() {
        // 获取所有用户
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        User user = userService.findById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(user);
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        User createdUser = userService.createUser(user);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        User updatedUser = userService.updateUser(id, user);
        if (updatedUser == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(updatedUser);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}

总结

Spring Boot中的RESTful API通过使用@GetMapping, @PostMapping, @PutMapping, 和 @DeleteMapping注解,使得每种HTTP请求类型都能简便地映射到控制器的方法上。

通过@RequestBody, @PathVariable, 和 @RequestParam处理请求参数,并利用返回对象或ResponseEntity构建响应,使得RESTful API的开发变得高效且易维护。

相关推荐

  1. Spring BootRESTful API详细介绍使用

    2024-06-13 06:38:04       31 阅读
  2. SpringBootWebSocket使用介绍

    2024-06-13 06:38:04       56 阅读
  3. Flutter AutomaticKeepAliveClientMixin 介绍使用

    2024-06-13 06:38:04       42 阅读
  4. SpringBoot常见注解详细介绍,附带代码示例

    2024-06-13 06:38:04       32 阅读
  5. NPM介绍使用详解

    2024-06-13 06:38:04       60 阅读
  6. C++匿名对象介绍使用场景详解

    2024-06-13 06:38:04       33 阅读
  7. python 断点调试 pdb 包介绍使用

    2024-06-13 06:38:04       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-13 06:38:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-13 06:38:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-13 06:38:04       82 阅读
  4. Python语言-面向对象

    2024-06-13 06:38:04       91 阅读

热门阅读

  1. spring boot logback.xml文件配置,info、error隔离

    2024-06-13 06:38:04       33 阅读
  2. MySQL 搭建主从报错 1236

    2024-06-13 06:38:04       28 阅读
  3. vue在hash路由模式下实现点击定位滑动

    2024-06-13 06:38:04       24 阅读
  4. 学习AI 机器学习,深度学习需要用到的python库

    2024-06-13 06:38:04       28 阅读
  5. 深度学习每周学习总结N1(one-hot 编码案例)

    2024-06-13 06:38:04       21 阅读
  6. 人脑神经元与AI神经网络的奥秘

    2024-06-13 06:38:04       30 阅读
  7. Android 10.0 framework层禁止扫描5g wifi功能实现

    2024-06-13 06:38:04       27 阅读
  8. 【无标题】

    2024-06-13 06:38:04       28 阅读
  9. k8s-CCE创建工作负载变量引用

    2024-06-13 06:38:04       29 阅读