Add prefix to URLs of all the controller classes in the package Add prefix to URLs of all the controller classes in the package spring spring

Add prefix to URLs of all the controller classes in the package


You might want to look at the convention over configuration support of Spring 3, specifically ControllerClassNameHandlerMapping. Effectively you don't define the location of the URL in a @RequestMapping but it's defined by the package location of the handler.

If you want to have the mapped URLs reflect the package name of controller then you should set the basePackage property of the ControllerClassNameHandlerMapping. The documentation says

Set the base package to be used for generating path mappings, including all subpackages underneath this packages as path elements. Default is null, using the short class name for the generated path, with the controller's package not represented in the path. Specify a base package like "com.mycompany.myapp" to include subpackages within that base package as path elements, e.g. generating the path "/mymodule/buyform" for the class name "com.mycompany.myapp.mymodule.BuyForm". Subpackage hierarchies are represented as individual path elements, e.g. "/mymodule/mysubmodule/buyform" for the class name "com.mycompany.myapp.mymodule.mysubmodule.BuyForm".

So, an example beans definition might be

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">    <property name="basePackage" value="com.company.project"/></bean><context:component-scan base-package="com.company.project.ws"/>

And your controllers might look like

package com.company.project.ws;@Controllerpublic class Service1 {    // your controller methods}


Another approach (very basic and simple) that I implemented was to define multiple Dispatcher servlets and then map different URLs for each servlet. The servlets share the root Spring context and in addition to that, have their own bean definitions. Read more in this Java doc.

So my web.xml looks like:

<servlet>    <servlet-name>flex</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup></servlet><!-- Mappings for BlazeDS requests --><servlet-mapping>    <servlet-name>flex</servlet-name>    <url-pattern>/spring/messagebroker/*</url-pattern></servlet-mapping><!-- Second dispatcher servlet for Web Services API --><servlet>    <servlet-name>wsapi</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>2</load-on-startup></servlet><servlet-mapping>    <servlet-name>wsapi</servlet-name>    <url-pattern>/spring/ws/*</url-pattern></servlet-mapping>

Basically, I left the existing dispatcher servlet as it is and added a new servlet only for REST controllers with different URL mapping. So I can control the URL for these servlets separately. After this, I no more need to put the URL prefix on each Controller.