多个 @RequestParam 参数设置默认值的写法
基本语法
每个 @RequestParam 都可以单独设置 defaultValue
属性:
例程:
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
public class testController {
// 多个参数,都有默认值
@RequestMapping("/test")
public String test(
@RequestParam(value = "name", defaultValue = "World") String name,
@RequestParam(value = "age", defaultValue = "18") Integer age,
@RequestParam(value = "city", defaultValue = "Beijing") String city) {
return String.format("Hello %s, age %d, from %s", name, age, city);
}
// 简化写法(参数名与变量名相同时)
@RequestMapping("/test2")
public String test2(
@RequestParam(defaultValue = "Guest") String name,
@RequestParam(defaultValue = "0") Integer score) {
return String.format("User: %s, Score: %d", name, score);
}
}
详细说明
1. 完整写法
@RequestParam(value = "参数名", defaultValue = "默认值") 数据类型 变量名
2. 简化写法(当参数名与变量名相同)
@RequestParam(defaultValue = "默认值") 数据类型 变量名
实际使用示例
// 搜索接口示例
@RequestMapping("/search")
public String search(
@RequestParam(defaultValue = "") String keyword, // 搜索关键词,默认空
@RequestParam(defaultValue = "1") Integer page, // 页码,默认第1页
@RequestParam(defaultValue = "10") Integer size, // 每页大小,默认10条
@RequestParam(defaultValue = "createTime") String sortBy, // 排序字段,默认按创建时间
@RequestParam(defaultValue = "desc") String sortOrder) { // 排序方向,默认降序
return String.format("搜索: %s, 第%d页, 每页%d条, 按%s %s排序",
keyword, page, size, sortBy, sortOrder);
}
// 用户信息接口示例
@RequestMapping("/userInfo")
public String getUserInfo(
@RequestParam(defaultValue = "0") Long userId,
@RequestParam(defaultValue = "false") Boolean includeDetails,
@RequestParam(defaultValue = "json") String format) {
return String.format("用户ID: %d, 包含详情: %s, 格式: %s",
userId, includeDetails, format);
}
注意事项
- 数据类型转换:Spring会自动进行类型转换
- 必需参数:如果不设置
defaultValue
,参数就是必需的 - 可选参数:设置了
defaultValue
的参数变为可选 - 布尔值默认值:
"true"
或"false"
(字符串形式) - 数字默认值:用字符串表示,如
"0"
、"100"
进阶用法
@RequestMapping("/advanced")
public String advanced(
@RequestParam(value = "q", defaultValue = "") String query,
@RequestParam(defaultValue = "1") @Min(1) Integer page,
@RequestParam(defaultValue = "10") @Range(min = 1, max = 100) Integer size,
@RequestParam(required = false) String category, // 可选参数,无默认值时为null
@RequestParam(defaultValue = "false") Boolean exact) {
// 处理逻辑
return "搜索结果";
}