Spring MVC multiple url mapping to the same controller method

孤者浪人 提交于 2019-12-05 21:29:24

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("/*");
    }
}

I had a situation where I cannot use /* mapping to dispatcher servlet, because I don't want all my requests of static resources to go to dispatcher servlet. So I used the below mapping to dispatcher servlet

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/spring/*</url-pattern>
</servlet-mapping>

and append the /spring to all your urls ex. http://localhost:8080/context/spring/common/get/currentuser

and your controller will look like below

@RestController

@RequestMapping("/common")

public class CommonController extends BaseController {

@RequestMapping(method = RequestMethod.GET,value="/get/currentuser")
public @ResponseBody User getUser() throws Exception  {
            // implementation ...

}


}


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!