Search This Blog

Friday 9 November 2012

Spring MVC without URL Mappings ?

In an earlier example we saw that Spring uses a single front-controller servlet. The Servlet then delegates the request to the controllers. This was achieved by mapping the controllers to urls.
<bean id="urlMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <value>
            /**/anything.do=defaultController
        </value>
    </property>
</bean>
Above we have mapped our bean ids to different URL expressions. It is not necessary to define a separate mapping bean at all times. We could have defined the above as follows:
<bean name="/**/anything.do" class="com.mvc.controller.DataWelcomeController"/>
The single line is sufficient to do the work of the above code. We have defined an instance of the controller bean and 'identified' it with the URL. Due to the special characters like slash and asterix the id would end up with an invalid value. Hence the name attribute is used.
In the above code Spring internally uses the BeanNameUrlHandlerMapping class to identify all such mappings. The code documentation for the class gives a very precise explanation of the various Mapping handlers available:
Implementation of the org.springframework.web.servlet.HandlerMapping
  interface that map from URLs to beans with names that start with a slash ("/"),
  similar to how Struts maps URLs to action names.
 
  This is the default implementation used by the
  {@link org.springframework.web.servlet.DispatcherServlet}, along with
  {@link org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping}
  (on Java 5 and higher). Alternatively, SimpleUrlHandlerMapping allows for
  customizing a handler mapping declaratively.
 
  The mapping is from URL to bean name. Thus an incoming URL "/foo" would map
  to a handler named "/foo", or to "/foo /foo2" in case of multiple mappings to
  a single handler. Note: In XML definitions, you'll need to use an alias
  name="/foo" in the bean definition, as the XML id may not contain slashes.
Other URL Handler mappings include:
  1. ControllerClassNameHandlerMapping
  2. CommonsPathMapHandlerMapping
in the next post we shall attempt to use multiple handler mappings together.

1 comment:

  1. Thanks for discussing this outstanding update. I was hunting for this variety of information and discovered it on your web site.
    custom cbd boxes uk
    Custom candle boxes
    url opener

    ReplyDelete