[英]Custom @JsonDeserialize on a @PathVariable of @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.