• Spring Boot 中常用的注解@RequestParam


    Spring Boot 中常用的注解@RequestParam

    @RequestParam 是 Spring Framework 和 Spring Boot 中常用的注解之一,用于从请求中获取参数值。它通常用于处理 HTTP 请求中的查询参数(query parameters)或表单数据。下面详细解释 @RequestParam 的用法:

    @RequestParam 的主要用法如下:

    1. 基本用法

      使用 @RequestParam 注解,您可以将请求中的参数绑定到方法的参数。例如,假设您有一个请求 URL http://example.com/api/user?id=123,您可以使用 @RequestParam 来获取 id 参数的值:

      @GetMapping("/api/user")
      public String getUserInfo(@RequestParam("id") int userId) {
          // 使用 userId 值来执行操作
          return "User ID: " + userId;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5

      在这个示例中,@RequestParam("id") 用于将 HTTP 请求中名为 id 的参数的值绑定到 userId 方法参数上。

    2. 默认值

      您可以为 @RequestParam 指定一个默认值,以便在参数未出现在请求中时使用默认值:

      @GetMapping("/api/user")
      public String getUserInfo(@RequestParam(name = "id", defaultValue = "1") int userId) {
          // 如果请求中没有 id 参数,userId 将默认为 1
          return "User ID: " + userId;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    3. 多个参数

      您可以使用多个 @RequestParam 注解来获取多个参数值

      @GetMapping("/api/user")
      public String getUserInfo(@RequestParam("id") int userId, @RequestParam("name") String userName) {
          // 使用 userId 和 userName 执行操作
          return "User ID: " + userId + ", User Name: " + userName;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    4. Map 接收多个参数

      如果您不知道参数的名称或希望一次接收多个参数,可以将参数封装到一个 Map 中:

      @GetMapping("/api/user")
      public String getUserInfo(@RequestParam Map<String, String> params) {
          String id = params.get("id");
          String name = params.get("name");
          // 使用 id 和 name 执行操作
          return "User ID: " + id + ", User Name: " + name;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
    5. 数组接收多个参数

      您还可以将多个参数绑定到数组或列表中:

      @GetMapping("/api/users")
      public String getUsersInfo(@RequestParam("id") int[] userIds) {
          // userIds 是一个整数数组,包含了请求中的所有 id 参数值
          return "User IDs: " + Arrays.toString(userIds);
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5

    总之,@RequestParam 注解是用于从 HTTP 请求中获取参数值的非常有用的注解,它允许您轻松地处理查询参数或表单数据,并将它们绑定到方法的参数上,以便在 Spring Boot 应用程序中进行处理。

  • 相关阅读:
    ant design vue对话框关闭数据清空
    多线程之生产者与消费者
    js 文字超过div宽度的时候,自动换行
    java maven pom application 生产prod/开发dev/测试test
    c++常见问题 2
    Linux文件权限修改
    C#通过反射方法实现依赖注入
    使用vscode进行远程编辑和调试
    【无标题】
    【ThreeJs】moving model
  • 原文地址:https://blog.csdn.net/Go_ahead_forever/article/details/133819364