spring-webmvc @RequestParam 典型用法

发布于:2025-06-21 ⋅ 阅读:(12) ⋅ 点赞:(0)

典型用法

基本使用

HTTP请求参数绑定到方法参数

@GetMapping("/users")
public String getUsers(@RequestParam String name) {
    return "Hello, " + name;
}

请求:/users?name=John
输出:Hello, John

-----

@GetMapping("/filter")
public String filter(@RequestParam String category, @RequestParam int limit) {
    return "Category: " + category + ", Limit: " + limit;
}

请求:/filter?category=books&limit=5

必选

@RequestParam 默认是必须传入的参数,否则会抛出异常。
可通过 required=false 设置为可选参数:

  @GetMapping("/optional")
  public String optionalParam(@RequestParam(required = false) String info) {
      return info != null ? info : "No info provided";
  }

设置默认值(defaultValue)

@GetMapping("/greet")
public String greet(@RequestParam(defaultValue = "Guest") String name) {
    return "Welcome, " + name;
}

请求:/greet(无参数)
输出:Welcome, Guest

指定参数名称(value / name)

@GetMapping("/search")
public String search(@RequestParam("query") String keyword) {
    return "Searching for: " + keyword;
}

请求:/search?query=spring
输出:Searching for: spring

接收数组或列表参数

@GetMapping("/ids")
public String getIds(@RequestParam List<Integer> ids) {
    return "IDs: " + ids;
}

请求:/ids?ids=1&ids=2&ids=3
输出:IDs: [1, 2, 3]

网站公告

今日签到

点亮在社区的每一天
去签到