Spring控制器与Postman请求报错:404/400问题排查求助
Spring RestController请求报错404/400的原因分析及解决
问题场景
使用以下Spring RestController代码时,发起请求遇到两类错误:
- 直接以
?user=xxx形式传参,返回404 NOT FOUND - 给参数值加括号(如
?user=(xxx)),返回400 BAD REQUEST
原代码
@RestController @RequestMapping("/gamification") public class GamificationController { private static final Logger logger = LoggerFactory.getLogger(GamificationController.class); @Autowired private GameServiceImpl gameService; @GetMapping("/retrieve-stats/?user={userId}") ResponseEntity<GameStats> getUserStats(@RequestParam("userId") String userId){ logger.debug("UserId is {}", userId); return ResponseEntity.ok(gameService.retrieveStatsForUser(Long.parseLong(userId))); } }
一、404 NOT FOUND的根本原因
@GetMapping注解里的路径配置完全错误:
你在路径里写了/retrieve-stats/?user={userId},但Spring中查询参数(Query Param)不需要嵌入在@GetMapping的路径字符串里。
Spring会把整个/retrieve-stats/?user={userId}当成一个固定的路径片段来匹配,只有请求URL的路径部分完全等于这个字符串时才会命中接口。但实际请求的路径是/gamification/retrieve-stats?user=xxx,和配置的路径不匹配,因此返回404。
二、400 BAD REQUEST的原因
当你给参数值加括号(如user=(123))时,即使路径碰巧匹配(比如你调整了路径),代码里的Long.parseLong(userId)会尝试把带括号的字符串转成Long类型,这会直接抛出NumberFormatException。Spring捕获到这个参数解析异常后,就会返回400 BAD REQUEST。
修正方案
- 修正
@GetMapping的路径,只保留资源路径,查询参数由@RequestParam处理 - 增加参数格式校验,避免因非法参数导致的异常
修正后的代码:
@RestController @RequestMapping("/gamification") public class GamificationController { private static final Logger logger = LoggerFactory.getLogger(GamificationController.class); @Autowired private GameServiceImpl gameService; // 路径仅保留资源标识,查询参数由@RequestParam接管 @GetMapping("/retrieve-stats") ResponseEntity<GameStats> getUserStats(@RequestParam("user") String userId){ logger.debug("UserId is {}", userId); // 先校验参数格式,避免NumberFormatException Long userIdLong; try { userIdLong = Long.parseLong(userId); } catch (NumberFormatException e) { logger.error("用户ID格式非法:{}", userId, e); return ResponseEntity.badRequest().build(); // 返回400并提示错误 } return ResponseEntity.ok(gameService.retrieveStatsForUser(userIdLong)); } }
修正后,发起/gamification/retrieve-stats?user=123这样的请求就能正常返回数据;如果传参格式错误(比如带括号、非数字),会返回友好的400响应。
内容的提问来源于stack exchange,提问作者IDK
相关产品推荐
相关产品推荐

