在Spring Boot的Web接口开发中,@RequestParam注解通常用于绑定请求中的参数,默认情况下该注解标注的参数是必传的,如果请求中没有携带对应参数,接口会直接返回400错误。实际业务里很多参数属于可选场景,比如分页查询时的页码参数、筛选条件参数等,不需要强制要求请求方传递,这时候就需要把@RequestParam设为可选参数。

方法一:设置required属性为false
@RequestParam注解自带required属性,默认值为true,代表参数必传。我们只需要把该属性设置为false,就可以让参数变为可选,请求中没有携带该参数时,参数值会为null。
示例代码如下:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test1")
public String test1(@RequestParam(value = "name", required = false) String name) {
if (name == null) {
return "未传递name参数";
}
return "传递的name参数为:" + name;
}
}
这种方式适合参数没有默认值,需要根据是否为null做不同逻辑处理的场景。
方法二:给参数指定默认值
如果可选参数在请求未传递时,希望有一个默认的取值,可以结合@RequestParam的defaultValue属性使用。当请求中没有携带对应参数时,参数会自动取defaultValue设置的值,不需要额外做null判断。
示例代码如下:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test2")
public String test2(@RequestParam(value = "page", defaultValue = "1") Integer page) {
return "当前页码为:" + page;
}
}
这里如果请求没有携带page参数,page的值会自动取1,适合有固定默认值的可选参数场景,比如分页查询的默认第一页。
方法三:使用包装类型接收参数
如果不设置required属性,也不设置默认值,只要使用对应的包装类型来接收参数,参数也会自动变为可选。因为基本类型无法接收null值,而包装类型可以,Spring Boot在绑定参数时,如果请求没有对应参数,会把包装类型参数赋值为null,不会报错。
示例代码如下:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test3")
public String test3(@RequestParam(value = "age") Integer age) {
if (age == null) {
return "未传递age参数";
}
return "传递的age参数为:" + age;
}
}
需要注意如果使用基本类型int来接收age参数,即使不设置required属性,请求没有传递age时还是会报错,所以必须使用包装类型Integer。
三种方式的适用场景对比
我们可以通过下面的表格快速判断不同场景下该选择哪种方式:
| 方式 | 适用场景 | 未传参数时的取值 |
|---|---|---|
| 设置required=false | 参数无默认值,需要根据是否为null处理不同逻辑 | null |
| 设置defaultValue | 参数有固定默认值,不需要额外做null判断 | defaultValue指定的值 |
| 使用包装类型接收 | 参数无默认值,且不想显式写required属性 | null |
注意事项
- 如果使用defaultValue属性,即使required属性设置为true,参数也会变为可选,因为默认值会生效,不需要请求传递参数。
- 当参数是基本类型时,不要直接使用基本类型接收可选参数,否则会出现参数缺失报错的问题,必须使用对应的包装类型。
- 如果参数需要支持多个值,比如同一个参数传递多个id,可以把参数类型设置为List,同样可以结合上述三种方式设置为可选参数。
示例多值可选参数的代码:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
@GetMapping("/test4")
public String test4(@RequestParam(value = "ids", required = false) List<Integer> ids) {
if (ids == null || ids.isEmpty()) {
return "未传递ids参数";
}
return "传递的ids为:" + ids;
}
}
Spring_BootRequestParam可选参数Java修改时间:2026-07-10 21:06:36