Spring MVC multiple url mapping to the same controller method

PickBoy picture PickBoy · Mar 18, 2016 · Viewed 13.6k times · Source

Let's say we have 3 url-patterns for a servlet named dispatcher in web.xml:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/aaa/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/bbb/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/ccc/*</url-pattern>
</servlet-mapping>

and a controller method:

@RequestMapping(value = "/xxx", method = RequestMethod.POST)
public String foo() {}

Since the path value in @RequestMapping does not contain servlet path, when users request

/aaa/xxx
/bbb/xxx
/ccc/xxx

the requests will all be mapped to method foo.

I think this could cause potential problem if the web site is very complicated. Is it a flaw in Spring Web MVC or I misunderstand something?

Answer

Braj picture Braj · Mar 18, 2016

You can map all requests to one request mapping by passing multiple value.

@RequestMapping(value = {"/aaa/xxx", "/bbb/xxx", "/ccc/xxx"}, method = RequestMethod.POST)
public String foo() {}

and just change mapping in web.xml to handle all type of request to dispatcher servlet.

<servlet-mapping>
   <servlet-name>dispatcher</servlet-name>
   <url-pattern>/*</url-pattern>
</servlet-mapping>

You can define different controllers based on application requirement or web flow. You can move common piece of code in utility classes if needed.

@RequestMapping("/aaa")
public class AAAController {
    @RequestMapping(value = "/xxx", method = RequestMethod.POST)
    public String foo() {
        // call to common utility function
    }
    // other methods
}

@RequestMapping("/bbb")
public class BBBController {
    @RequestMapping(value = "/xxx", method = RequestMethod.POST)
    public String foo() {
        // call to common utility function
    }
    // other methods
}

@RequestMapping("/ccc")
public class CCCController {
    @RequestMapping(value = "/xxx", method = RequestMethod.POST)
    public String foo() {
        // call to common utility function
    }
    // other methods
}

Read more in Spring Web MVC framework documentation

You can configure it programatically as well

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/*");
    }
}