Search code examples
springjspjstljsp-tagsspring-4

How to specify the controller name if two controllers have same RequestMapping path value?


There are 2 controllers having same @RequestMapping value :

package com.ambre.hib.controller;
@Controller
public class AppointmentsController {
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }
}

package com.ambre.hib.controller;
@Controller
public class ClientsController {
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public ClientForm getNewForm() {
        return new ClientForm();
    }
}

So the 2 controllers have same "/new" action.

Now from a jsp page I want to target a link to the "/new" action of the second controller : <a href="<c:url value='/new' />"><img src="resources/images/plus.png" /></a>

This writing is ambiguous because Spring does not know into which controller to look ! So how to specify the controller name in the link target ?


Solution

  • It's not possible to have two or more controller methods with the same @RequestMapping. The dispatcher won't know wich method to call.

    You could set a base request mapping for each controller:

    package com.ambre.hib.controller;
    @Controller
    @RequestMapping("/appointments")
    public class AppointmentsController {
        @RequestMapping(value = "/new", method = RequestMethod.GET)
        public AppointmentForm getNewForm() {
            return new AppointmentForm();
        }
    }
    
    package com.ambre.hib.controller;
    @Controller
    @RequestMapping("/clients")
    public class ClientsController {
        @RequestMapping(value = "/new", method = RequestMethod.GET)
        public ClientForm getNewForm() {
            return new ClientForm();
        }
    }
    

    If so, the way of calling each would be <a href="<c:url value='/appointments/new' />"> for the first controller and <a href="<c:url value='/clients/new' />"> for the second