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

时间:2018-08-05 12:28:15

标签: java spring rest spring-mvc spring-boot

我有以下问题:

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我在网址下方找到了解决方案。

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";
    }
}