Spring MVC 3 : Ambiguous mapping found

Amit Patel picture Amit Patel · Jan 18, 2012 · Viewed 48.4k times · Source

I am playing with spring MVC 3.1 and testing different features. I wanted to verify following statement taken from @RequestMapping#value doc

If you have a single default method (without explicit path mapping), then all requests without a more specific mapped method found will be dispatched to it. If you have multiple such default methods, then the method name will be taken into account for choosing between them

So I created following controller with multiple default handler methods.

@Controller
@RequestMapping("/book")
public class BookController {

    @RequestMapping
    public @ResponseBody String greet() {
        return "Hi Book!";
    }

    @RequestMapping
    public @ResponseBody String meet() {
        return "Nice to meet you Book!";
    }
}

Here is web application context configuration

<beans ....>
<!-- Use @Component annotations for bean definitions -->
  <context:component-scan base-package="com.botreeconsulting.lms.web"/>

  <!-- Use @Controller annotations for MVC controller definitions -->
  <mvc:annotation-driven />

  <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
   </bean>

</beans>

But it seems I messed up something as it is giving me following error at the time of deployment:

java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'bookController' bean method 
public java.lang.String com.botreeconsulting.lms.web.BookController.meet()
to {[/book],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'bookController' bean method
public java.lang.String com.botreeconsulting.lms.web.BookController.greet() mapped.

Now the question is does this controller models what is written in the document? I feel that I didn't get it properly. Please guide me to model the controller to match the statement about multiple default handlers.

Thanks, Amit

Answer

Arun P Johny picture Arun P Johny · Jan 18, 2012

If you have a controller as given below, all requests other than /book/edit will be directed to mydefault() while /book/edit will be sent to meet().

@Controller
@RequestMapping("/book")
public class BookController {

    @RequestMapping
    public @ResponseBody String mydefault() {
        return "Hi Book!";
    }

    @RequestMapping("/edit")
    public @ResponseBody String meet() {
        return "Nice to meet you Book!";
    }
}

In your sample you have two methods without explicit path mapping.