重载包含不同路径变量类型的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)}

SK

在Spring MVC中,基于PathVariable类型的重载将是不可能的,因为两个API都将被视为相同。在运行时,将为您提到的任何请求找到两个处理程序,因此会发现异常。

您可以改为删除getById()方法,并且第二个API也将适用于单个ID。唯一的区别是返回类型将是一个列表,并且可以在客户端轻松处理。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

基于目录的不同路径

appendPathComponent(_:) 后的不同路径

从同一模块的不同导入中获得的Rust,相同类型,不同路径

laravel中具有不同参数的不同路径到相同方法

包含在相同路径中的信息

具有不同返回类型的方法重载

Marathon-lb 不同路径的规则

Python 从不同路径导入类

多个不同路径的JSONPath联合

whereis返回到的不同路径

从不同路径运行Wordpress / NGINX

如何使用JProfiler检测和测量通往特定方法的不同路径?

C# MVC 使用 AJAX 调用不同路径中的方法

较少具有不同变量类型的重载mixin

在相同路径的相对路径上,“文件名与仅包含在壳体中的已包含文件名不同”

LexikJWTAuthenticationBundle - 如何授予对不同路径的不同访问权限?

Traefik + Docker反向代理-针对不同路径的不同Auth?

Laravel:不同路径的API速率限制不同

如何使用pactjs处理不同环境的不同路径参数

从ArrayList中获取包含不同类型的List的变量的好方法吗?

Spring Boot-将GetMapping简化为具有不同路径的相同方法的简便方法

重载相同的方法以打印不同的数据类型arraylist

python中不同参数类型的方法重载

在方法重载中传递不同数据类型的值

Angular-Cli:开发和发布输出的不同路径

重定向到不同域中的相同路径

在USQL中联接来自不同路径的文件

产品图像从前端和后端的不同路径提供

使用Rails和Webpacker在不同路径下构建资产