Search code examples
springrestspring-mvccontrollerrestful-architecture

Spring REST multiple controllers for one URL but different http methods


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.


Solution

  • 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.