@RequestParam
是 Spring Framework 中的一个注解,用于将 HTTP 请求参数绑定到控制器方法的参数上。它主要用于处理 GET 和 POST 请求中的查询参数和表单数据。
基本用法
@RequestParam
注解可以应用于控制器方法的参数上,以便将请求参数绑定到方法参数。以下是一些基本用法示例:
1. 绑定单个请求参数
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/greet")
public String greet(@RequestParam("name") String name) {
return "Hello, " + name + "!";
}
}
在这个示例中,@RequestParam("name")
注解将请求参数 name
绑定到方法参数 name
上。如果请求 URL 是 http://localhost:8080/greet?name=John
,那么 name
参数的值将是 John
。
2. 绑定多个请求参数
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/greet")
public String greet(@RequestParam("name") String name, @RequestParam("age") int age) {
return "Hello, " + name + "! You are " + age + " years old.";
}
}
在这个示例中,@RequestParam("name")
和 @RequestParam("age")
注解将请求参数 name
和 age
绑定到方法参数 name
和 age
上。如果请求 URL 是 http://localhost:8080/greet?name=John&age=30
,那么 name
参数的值将是 John
,age
参数的值将是 30
。
3. 设置默认值
如果请求参数没有提供,可以使用 defaultValue
属性来设置默认值。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/greet")
public String greet(@RequestParam(value = "name", defaultValue = "Guest") String name) {
return "Hello, " + name + "!";
}
}
在这个示例中,如果请求 URL 没有提供 name
参数,那么 name
参数的默认值将是 Guest
。
4. 设置是否必需
可以使用 required
属性来指定请求参数是否必需。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/greet")
public String greet(@RequestParam(value = "name", required = false) String name) {
if (name == null) {
name = "Guest";
}
return "Hello, " + name + "!";
}
}
在这个示例中,required = false
表示 name
参数是可选的。如果请求 URL 没有提供 name
参数,那么 name
参数的值将是 null
。
总结
@RequestParam
注解是 Spring Framework 中的一个强大工具,用于将 HTTP 请求参数绑定到控制器方法的参数上。通过使用 @RequestParam
注解,可以方便地处理 GET 和 POST 请求中的查询参数和表单数据。理解 @RequestParam
注解的用法和属性,可以帮助你更好地处理和验证请求参数。