×
☰ See All Chapters

SimpleUrlHandlerMapping

SimpleUrlHandlerMapping is a simple way to define URL mapping using a map or property bean. Mapping more than one URL to a single controller class is possible by using SimpleUrlHandlerMapping. Mapping more than one URL to a single controller is not a good way to work with spring dependency injection, when we use default BeanNameUrlHandlerMapping. SimpleUrlHandlerMapping defines the navigation strategy that maps the servlet-path/URI of the URL to the mappings configured in given properties or map. In this case we need to inject properties or map object that describes the mappings between the request URL path and Controllers. SimpleUrlHandlerMapping supports two options to configure the mappings.

  1. First is provide a map instance to SimpleUrlHandlerMapping by setting the property “urlMap”, in which the key of the entry will be URL and value will be the controller class. We can also provide value-ref to indicate controller bean. 

  2. Second is to set the instance of java.util.Properties to the property “mappings”, in which the key will be the URL and value will be the id of the controller bean. 

If we open the source code of SimpleUrlHandlerMapping we can see fields urlMap and mappings shown as below:

class SimpleUrlHandlerMapping   {

      private final  Map<StringObject> urlMap ;

      private final  Properties mappings ;

      ….  ….

}

SimpleUrlHandlerMapping Example:

</beans>

    <bean id="helloController" class="com.java4coding.controller.HelloController"/>

    <bean id="haiController" class="com.java4coding.controller.HaiController"/>

    <bean id="myController" class="com.java4coding.controller.MyController"/>

    <bean id="urlHandler" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

        <property name="urlMap">

            <map>

                <entry key="/hello.htm" value-ref="helloController"/>

                <entry key="/sayHello*" value-ref="haiController "/>

            </map>

        </property>

        <property name="mappings">

            <props>

                <prop key="/welcome.htm">myController</prop>

                <prop key="/welcomeUser*">helloController</prop>

            </props>

        </property>

    </bean>

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

        <property name="prefix" value="/WEB-INF/jsp/"/>

        <property name="suffix" value=".jsp"/>

    </bean>

</beans>

 

The key can define any static url as “/hello.htm’ and as well as urls containing * to denote any number of character can replace that *.


All Chapters
Author