重载包含不同路径变量类型的 RestController 方法

我有以下问题:


我有一个 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)}


ABOUTYOU
浏览 225回答 2
2回答

慕村9548890

在 Spring MVC 中,基于 PathVariable 类型的重载将是不可能的,因为这两个 API 将被认为是相同的。在运行时,将为您提到的任何请求找到两个处理程序,因此会出现异常。您可以改为删除 getById() 方法,第二个 API 也适用于单个 ID。唯一的区别是返回类型将是一个 List 并且可以在客户端轻松处理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java