[英]Request handler is executed, but response status is always 404
我有一個簡單的Web控制器,它處理對GET /base/{userId}/test/{userId}
請求(例如GET /base/1/test/2
),並返回一個對象,該對象以后應轉換為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-Not found”的響應。 我已經調試了代碼,並確定TestService
服務和Response#ok()
方法運行正常。
然后,我調試了Spring Framework源代碼,發現出於某種未知的奇怪原因,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
。
其他混亂的請求屬性是: strippedServletPath
, requestDispatcherPath
, requestUri
。 為了簡潔起見,我不會將它們放在答案正文中
您只是忘了將@ResponseBody
批注放在getTest()
方法上。
指示方法返回值的注釋應綁定到Web響應正文。
此代碼應工作:
@GetMapping("/test/{testId}")
@ResponseBody
public Response<TestDto> getTest(@PathVariable("userId") Long userId, @PathVariable("testId") Long testId) {
return Response.ok(testService.get(userId));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.