簡體   English   中英

重載包含不同路徑變量類型的 RestController 方法

[英]Overloading RestController methods that include different pathvariable types

我有以下問題:

我有一個 Rest 控制器,我想在以下 URL 中配置它:

/api/districts/1,2,3 - (按 id 數組列出地區)

/api/districts/1 - (按單個 id 列出地區)

這些是以下映射方法:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public District getById(@PathVariable int id) {
    // check input

    return districtService.getById(id);
}

@RequestMapping(value = "/{districtIDs}", method = RequestMethod.GET)
public List<District> listByArray(@PathVariable Integer[] districtIDs) {
    ArrayList<District> result = new ArrayList<>();

    for (Integer id : districtIDs) {
        result.add(districtService.getById(id));
    }

    return result;
}

這是我向/api/districts/1,2,3發出請求時遇到的錯誤

There was an unexpected error (type=Internal Server Error, status=500). Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/api/districts/1,2,3': {public java.util.List com.groto.server.web.DistrictsController.listByArray(java.lang.Integer[]), public com.groto.server.models.hibernate.District com.groto.server.web.DistrictsController.getById(int)}

這是我向/api/districts/1發出請求時遇到的錯誤

There was an unexpected error (type=Internal Server Error, status=500). Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/api/districts/1': {public java.util.List com.groto.server.web.DistrictsController.listByArray(java.lang.Integer[]), public com.groto.server.models.hibernate.District com.groto.server.web.DistrictsController.getById(int)}

在 Spring MVC 中,基於 PathVariable 類型的重載將是不可能的,因為這兩個 API 將被認為是相同的。 在運行時,將為您提到的任何請求找到兩個處理程序,因此會出現異常。

您可以改為刪除 getById() 方法,第二個 API 也適用於單個 ID。 唯一的區別是返回類型將是一個 List 並且可以在客戶端輕松處理。

我在 url 下找到了解決方案。

https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-path-variable.html

/**
 * Using mutually exclusive regex, which can be used
 * to avoid ambiguous mapping exception
 */
@Controller
@RequestMapping("/dept")
public class DeptController {

    @RequestMapping("{id:[0-9]+}")
    public String handleRequest(@PathVariable("id") String userId, Model model){
        model.addAttribute("msg", "profile id: "+userId);
        return "my-page";

    }

    @RequestMapping("{name:[a-zA-Z]+}")
    public String handleRequest2 (@PathVariable("name") String deptName, Model model) {
        model.addAttribute("msg", "dept name : " + deptName);
        return "my-page";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM