You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中@RequestParam defaultValue覆盖用户入参问题排查及解决

Spring Boot @RequestParam 参数始终取默认值问题解决

问题描述

使用Spring Boot开发接口时,@RequestParam注解配置了required = false和默认值,即使用户主动传入对应参数,后台获取到的参数值始终是默认值。
示例注解配置如下:

@RequestParam(name = "findBy", required = false, defaultValue = "id") String findBy

比如前端发送请求/api?findBy=userName,预期后台拿到的findBy值为userName,实际拿到的始终是默认值id。

完整控制器代码

@RestController
@RequestMapping("/api")
public class PostsController {

    @Autowired
    FindService findService = new FindService();

    @GetMapping
    public Object getPosts(@RequestParam(name = "findBy", required = false, defaultValue = "id") String findBy,
                           @RequestParam(name = "sortBy", required = false, defaultValue = "userName") String sortBy,
                           @RequestParam(name = "tags") String... tags) {

        System.out.println("Inside FindController, findBy: " + findBy);
        System.out.println("Inside FindController, sortBy: " + sortBy);

        return findService.getPostsList(findBy, sortBy, tags);
    }
}

排查过程

由于服务层findService.getPostsList返回结果不符合预期,在控制器中添加入参打印日志,确认findBy和sortBy两个参数无论传入什么值,后台都始终读取注解配置的默认值。

问题根因

请求URL的参数分隔符书写错误:多个查询参数需要使用&分隔,错误写法用了第二个?做分隔:

  • 错误请求:http://localhost:8080/api?findBy=username?sortBy=lastname
  • 修正后正确请求:http://localhost:8080/api?findBy=username&sortBy=lastname

修正分隔符后即可正常接收传入的参数值,仅当参数未传递时才会走注解配置的默认值。


内容的提问来源于stack exchange,提问作者Woodsoul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:18:00