14
votes

In Spring MVC 3 I want to handle the same url with two different controller classes - depending on value of url parameter. @RequestMapping annotation even has such field: params, and I thought following would be two different mappings (I use mapping on class level):

@RequestMapping(value = "/myurl", params = "name=val1")

and

@RequestMapping(value = "/myurl", params = "name=val2")

but it's not. Spring throws exception for second case that controller for /myurl already mapped (by first case).

Is there some accurate solution for splitting request mapping by parameter? May be extending @RequestMapping or using proxy as controller and call different controllers depending on parameter... Any thoughts?

UPDATE This works but only on methods level, not on class level... This will:

@Controller
@RequestMapping(value = "/myurl")
public class Class123 {

    @RequestMapping(value = {"edit.htm"}, params = "src=1")
    public String open1(Map<String, Object> map) throws Exception {....}

    @RequestMapping(value = {"edit.htm"}, params = "src=2")
    public String open2(Map<String, Object> map) throws Exception {....}
}

this won't:

@Controller
@RequestMapping(value = "/myurl", params = "src=1")
public class Class123_1 {

    @RequestMapping(value = {"edit.htm"})
    public String open(Map<String, Object> map) throws Exception {....}
}


@Controller
@RequestMapping(value = "/myurl", params = "src=2")
public class Class123_2 {

    @RequestMapping(value = {"edit.htm"})
    public String open(Map<String, Object> map) throws Exception {....}
}

And I would like to split logic in different classes.

1
That should work. I've used it, it works. Something else is going on that you haven't shown us. Perhaps some other controller has mapped that URL. - skaffman
Hmm, maybe this only works for methods in the same class. Not sure if that's a bug or not, though, although the documentation doesn't mention it. Perhaps you could keep the methods in one class, but then delegate to another class to keep the implementations separate? - skaffman
I don't think it's a bug. May be problem is that I dont define default mapping, narrowing down from class to methods (smth like /myurl/*) Following this direction about delegating I thought about making kind of proxy class that will call one of implementations for appropriate method. But this want simplify my task for sure - crudo6

1 Answers

2
votes

It sounds like a difference between using RequestMappingHandlerMapping (new in Spring 3.1) vs DefaultAnnotationHandlerMapping (the class replaced by RequestMappingHandlerMapping).