我想在 Java 中實現一個帶有“重載”端點的 REST API,該端點因傳遞的查詢參數而異。我在我的控制器類中嘗試過這段代碼:@Get("/query")public MyResponse queryByDate(@QueryValue @Valid @Format("yyyy-MM-dd") Date date) { // Code to generate the response return retval;}@Get("/query")public MyResponse queryByDateAndValue(@QueryValue @Valid @Format("yyyy-MM-dd") Date date, @QueryValue int value) { // Code to generate the response return retval;}這將返回以下錯誤:More than 1 route matched the incoming request. The following routes matched /calendar/years/query: GET - /calendar/years/query, GET - /calendar/years/queryio.micronaut.web.router.exceptions.DuplicateRouteException: More than 1 route matched the incoming request. The following routes matched /calendar/years/query: GET - /calendar/years/query, GET - /calendar/years/query請注意,如果我刪除其中一種方法,其余方法將按預期工作。如何將具有不同查詢參數的端點映射到控制器中的 2 個不同方法?這可能嗎?
1 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
您收到錯誤是因為兩個端點具有相同的路徑,并且它會混淆編譯器將 API 映射到相應的路徑。傳遞查詢參數并不意味著端點具有不同的路徑。您可以將這兩個端點合二為一:
@Get("/query")
public MyResponse queryByDateAndValue(@QueryValue @Valid @Format("yyyy-MM-dd") Date date,@DefaultValue("1") @QueryValue int value) {
// Code to generate the response
return retval;
}
并設置默認值value。然后您可以相應地分開您的案例。
添加回答
舉報
0/150
提交
取消