请求处理程序已执行,但响应状态始终为 404

Request handler is executed, but response status is always 404

我有一个简单的 Web 控制器,可以处理对 GET /base/{userId}/test/{userId}(例如 GET /base/1/test/2)和 returns 的请求,该对象稍后应转换为 JSON。

@Controller
@RequestMapping("/base/{userId}")
public class TestController {

    @Autowired
    TestService testService;

    @GetMapping("/test/{testId}")
    Response<TestDto> getTest(@PathVariable("userId") Long userId, @PathVariable("testId") Long testId) {
        return Response.ok(testService.get(userId));
    }

}

但每当我调用它时,都会得到“404 - 未找到”的响应。我调试了我的代码,我确定 TestService 服务和 Response#ok() 方法工作正常。

然后我调试了 Spring 框架源,发现由于某些未知的奇怪原因 Spring 的内部 过滤器链被执行了两次 和第二次执行时请求 URI 混乱(URI 重复)。例如,在第一次执行时我有 request.servletPath = "/base/1/test/2",在随后的执行中我有 request.servletPath = "/base/1/base/1/test/2" (* 请参阅下面的注释)。然后返回提到的 404 错误,显然我的应用程序中没有 /base/1/base/1/test/2 的映射。

出了什么问题,我该如何解决?


* request 在这里是 ApplicationHttpRequest 类型。
其他混乱的请求属性是:strippedServletPathrequestDispatcherPathrequestUri。为了简洁起见,我没有将它们放在答案正文中

您只是忘了在您的 getTest() 方法上添加 @ResponseBody 注释。

Annotation that indicates a method return value should be bound to the web response body.

此代码应该有效:

@GetMapping("/test/{testId}")
@ResponseBody
public Response<TestDto> getTest(@PathVariable("userId") Long userId, @PathVariable("testId") Long testId) {
    return Response.ok(testService.get(userId));
}