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

Spring Boot POST请求后陷入无限循环问题求助

Spring Boot请求映射失败+无限循环StackOverflow问题解决

问题场景

Spring Boot应用上下文为myContext,控制器代码如下:

@RestController
@RequestMapping("/api/v1")
@Slf4j
public class MyController {

    @SecurityRequirement(name = "OpenId")
    @PostMapping(path = "/record/import", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> importRecord(@RequestBody RecordJson importBody, Authentication auth, Locale locale) throws ParseException {
    ...
    }
}

用Postman发送POST localhost:8080/myContext/api/v1/record/import请求时,应用陷入无限循环,日志反复输出:

2023-04-03 14:57:45.229  WARN 22976 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound             : No mapping for POST /myContext/
2023-04-03 14:57:45.232  INFO 22976 --- [nio-8080-exec-1] c.n.a.e.c.ForwardConfiguration           : No requested mapping found. Forwarding to index

最终抛出StackOverflowError,但其他接口可正常工作。


问题1:请求无法映射到控制器的排查点

  • 核对请求头:确保Postman的Content-Type设为application/json,接口指定了consumes = MediaType.APPLICATION_JSON_VALUE,请求头不匹配会直接跳过该映射。
  • 检查请求体结构:确认请求JSON与RecordJson实体字段完全匹配,序列化失败可能导致Spring找不到对应方法(一般返回400,但也可能触发无映射逻辑)。
  • 排查认证配置:接口添加了@SecurityRequirement(name = "OpenId"),检查OpenId认证是否配置正确,认证失败后若被重定向到其他路径,会导致原请求路径未被匹配。
  • 路径匹配规则:检查Spring Boot的路径匹配策略(比如spring.mvc.pathmatch.matching-strategy配置),确认没有拦截器或过滤器篡改了请求路径。

问题2:无限循环的解决办法

循环根源是ForwardConfiguration在无映射时转发到index,但/myContext/的POST请求也没有对应映射,导致反复转发。解决方式:

  1. 修改转发逻辑:
    找到ForwardConfiguration类,限制只对GET请求执行转发,其他请求直接返回404,示例代码:
    @ControllerAdvice
    public class ForwardConfiguration {
        // 仅处理GET请求的转发逻辑
        @RequestMapping(value = "/**", method = RequestMethod.GET)
        public String forwardToIndex() {
            return "forward:/index";
        }
    }
    
  2. 全局处理404异常:
    自定义异常处理器替代默认转发逻辑,彻底避免循环:
    @ControllerAdvice
    public class GlobalNotFoundHandler {
        @ExceptionHandler(NoHandlerFoundException.class)
        public ResponseEntity<String> handleNoMapping(NoHandlerFoundException ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("请求路径不存在");
        }
    }
    
    同时在application.properties中添加配置:
    spring.mvc.throw-exception-if-no-handler-found=true
    spring.web.resources.add-mappings=false
    

快速验证方案

先临时注释掉@SecurityRequirement注解,去掉认证限制后发送请求,确认是否能正常映射到控制器,排除认证导致的路径跳转问题。

内容的提问来源于stack exchange,提问作者andrejb-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:39:53