Spring REST 多个控制器用于一个 URL 但不同的 http 方法
我目前有一个控制器可以处理 URL 组的 GET 和 POST:
@Controller
public class RestGroups {
...
@RequestMapping(method = RequestMethod.GET, value = "/groups")
@ResponseBody
public GroupsDto groups() {
return new GroupsDto(getGroups());
}
@RequestMapping(method = RequestMethod.POST, value = "/groups", headers = "Accept=application/xml")
@ResponseBody
public GroupsDto postGroup(@RequestBody GroupDto groupDto) {
groupSaver.save(groupDto.createEntity());
return groups();
}
现在我想要两个控制器,两个控制器都分配给相同的 URL,但每个控制器分配给不同的方法,如下所示:
@Controller
public class GetGroups {
...
@RequestMapping(method = RequestMethod.GET, value = "/groups")
@ResponseBody
public GroupsDto groups() {
return new GroupsDto(getGroups());
}
...
}
@Controller
public class PostGroup {
...
@RequestMapping(method = RequestMethod.POST, value = "/groups", headers = "Accept=application/xml")
@ResponseBody
public GroupsDto postGroup(@RequestBody GroupDto groupDto) {
groupSaver.save(groupDto.createEntity());
return groups();
}
...
}
可能吗?因为现在我得到 Spring 异常,一个 URL 无法由两个不同的控制器处理。这个问题有解决方法吗?我真的很想将这两个完全不同的操作分成两个单独的类。
I currently have one controller that handles both GET and POST for URL groups:
@Controller
public class RestGroups {
...
@RequestMapping(method = RequestMethod.GET, value = "/groups")
@ResponseBody
public GroupsDto groups() {
return new GroupsDto(getGroups());
}
@RequestMapping(method = RequestMethod.POST, value = "/groups", headers = "Accept=application/xml")
@ResponseBody
public GroupsDto postGroup(@RequestBody GroupDto groupDto) {
groupSaver.save(groupDto.createEntity());
return groups();
}
Now I would like to have TWO controllers, both assigned for same URL but each for different method, something like below:
@Controller
public class GetGroups {
...
@RequestMapping(method = RequestMethod.GET, value = "/groups")
@ResponseBody
public GroupsDto groups() {
return new GroupsDto(getGroups());
}
...
}
@Controller
public class PostGroup {
...
@RequestMapping(method = RequestMethod.POST, value = "/groups", headers = "Accept=application/xml")
@ResponseBody
public GroupsDto postGroup(@RequestBody GroupDto groupDto) {
groupSaver.save(groupDto.createEntity());
return groups();
}
...
}
Is it possible? Because now I get Spring exception that one URL cannot be handled by two different controllers. Is there a workaround for this issue? I really would like to separate those two completely different actions into two separate classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Spring 3.1 中通过新的 HandlerMethod 抽象解决了这个限制。您必须升级到 3.1.M2。如果您需要示例,请告诉我。
This limitation has been solved in Spring 3.1 with its new HandlerMethod abstraction. You'll have to upgrade to 3.1.M2. Let me know if you need an example.