Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention over configuration with Spring MVC using ControllerClassNameHandlerMapping?

Following the directions from Spring Source and the book Spring in Action, I am trying to set up Spring MVC in a way that minimizes xml configuration. However according to Spring Source this is how you set up the ControllerClassNameHandlerMap

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="viewShoppingCart" class="x.y.z.ViewShoppingCartController">
    <!-- inject dependencies as required... -->
</bean>

Which strikes me as being completely useless, as it is actually simpler to use the handlers to just set the beans manually, as it is about the same amount of XML.

Now the book Spring in Action makes it sound like all you need is the first line from that code block to use the ControllerClassNameHandlerMapping, which would make it far more useful. However, I have not yet been able to get this to work.

Can anyone with Spring experience help me out?

like image 758
James McMahon Avatar asked Feb 28 '23 21:02

James McMahon


1 Answers

There are actually two different things going on here:

  1. the mapping between URLs and controllers
  2. the definition of controllers as Spring beans

For #1, if you define the ControllerClassNameHandlerMapping as you've done, that takes care of the URL-to-controller mapping. E.g., http://example.com/context/home -> HomeController

For #2, you can define the controller beans as you've done. Or you can go down the path of using the Spring 2.5-style annotations for @Controllers and auto-wiring, which eliminates the need for XML bean definitions. Or not, the choice is up to you.

What you avoid by using ControllerClassNameHandlerMapping is having to explictly map all your potential URLs to Controllers. We have used this successfully.

One other thing you might want to use is the DefaultRequestToViewNameTranslator:

<!-- Generates view names based on the request url (e.g. "/home.htm" => "home", "/user/list.htm" => "user/list", etc.) -->
<bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/>

We also use the UrlBasedViewResolver:

<!-- Maps view names to tiles view definitions files.  E.g., "home" => "home", etc.  -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
like image 162
Jeff Olson Avatar answered Mar 05 '23 16:03

Jeff Olson