Books

Tuesday, April 15, 2014

Configuring Spring MVC

tl;dr The process of configuring Spring MVC involves configuring the DispatcherServler as a front controller in the web.xml and configuring the Spring context file where Spring MVC specific beans like Controllers, Handler mappings, View resolvers, Locale resolver and Theme resolver can be wired.

This post is about how to configure Spring MVC. It is part of the Configuring Spring Series.

Spring MVC allows you to put the Spring framework at the fore front of your web layer. As you probably know, it is possible to use Spring in a web application without Spring MVC. As mentioned in Configuring Beans In Spring Framework, you can use WebApplicationContextUtils to bring in the Spring context into your web application. In that scenario, Spring is not responsible for the whole Web layer, it just plays its part, mostly as a DI container. But with Spring MVC, Spring framework is put at a central and integral part of your web layer.

Dependencies


I would be using Maven for dependency management. To get Spring MVC, certain required artifacts needs to be added to your project. To get these dependencies with Maven, your pom.xml file may look thus:




        4.0.1.RELEASE
    

    
        
            junit
            junit
            3.8.1
            test
        

        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        

        
            org.springframework
            spring-webmvc
            ${spring.version}
        
    



Adding these dependencies could be achieved manually or via any other dependency/build tool. Irrespective of which tool you use, once these dependencies are available, you can proceed to configuration.

Configuring the web.xml


The web.xml file is the Web Application Deployment Descriptor of your application and it defines everything about your application. The configuration specified in the web.xml is used by whatever server your web application is deployed in. It is located in /WEB-INF/web.xml.

For an overview of the available configuration available in the web.xml file, I find this reference guide on web.xml by Meta Werx more than sufficient.

Our configuration of Spring MVC starts here: at the web.xml.



The figure above is a representation of what is usually refereed to as Front Controller Pattern. It is mostly used in the design of web applications in which you get to have one central and entry point into your application.

Spring MVC is designed using this pattern and as such our configuration in web.xml starts by configuring this central entry point.

In Spring MVC, this central entry point is called the DispatcherServlet. Going by the name, the DispatcherServlet is obviously a Servlet and so, it is configured as such.

It is during its configuration that you pass in the Spring Contexts, the other important part of configuring Spring MVC flow.

A DispatcherServlet configured in a web.xml may look like this:



 
  
   mvc-dispatcher 
   org.springframework.web.servlet.DispatcherServlet
   
       contextConfigLocationWEB-INF/spring_conf/web-mvc-layer.xml

   1  
  
      
   
 
    mvc-dispatcher
    /*
 




or



  
   
     mvc-dispatcher 
     org.springframework.web.servlet.DispatcherServlet
     1  
   
      
    
  
      dispatcher
      /*
    


The difference between the two configurations is how the location of the Spring context configuration is specified.

In the second example the <init-param/> tag is removed. In which case the Spring configuration file needs to be renamed and placed in /WEB-INF directory. This is because after initializing the DispatcherServlet, Spring MVC by default looks to wire up beans in a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application (hence /WEB-INF/mvc-dispatcher-servlet.xml in out example). But with the first option you can have the name of the Servlet not depict the Spring configuration file and then use contextConfiguration to explicitly set where the Spring Configuration file can be located. I personally prefer explicity; so I tend to go with the first method.

The other things to note in the web.xml configuration is the <servlet-mapping/>. It specify which requests, depending on the URL, to route through the DispatchServlet. In our example, having <url-pattern>/</url-pattern> means all requests would be routed through the DispatchServlet.

That's it with the web.xml configuration, lets move to Spring configuration.


Configuring the Spring Context


The Spring configuration file specified in the web.xml needs to be configured. When configured, it is mainly used to define Spring-MVC specific beans. And these beans are:

Controllers
Controllers are the components that form the 'C' part of the MVC.

Handler mappings
Handler mappings handle the execution of a list of pre- and post-processors and controllers that will be executed if they match certain criteria (for instance a matching URL specified with the controller).

View resolvers
View resolvers are components capable of resolving view names to views.

Locale resolver
A locale resolver is a component capable of resolving the locale a client is using, in order to be able to offer internationalized views.

Theme resolver
A theme resolver is capable of resolving themes web application themes.

Handler exception resolver(s)
Handler exception resolvers offer functionality to map exceptions to views or implement other more complex exception handling code.

For more information about these bean types, read the Spring MVC guide

for our example, the Spring configuration could look thus:



  

  
     
     
  


Here, we explicitly configure one, out of the six Spring MVC specific beans: the View Resolver.

Note the <context:component-scan base-package="com.myspringapp" /> configuration. This allows us to configure controllers, not from the Spring Configuration files itself, but by annotating classes within com.myspringapp package with the @Controller annotation.

This is referred to as auto-scanning of components. The other Spring configuration tag/namespace that can enable this is <mvc:annotation-driven />. With  <context:component-scan base-package="com.myspringapp" /> you get this functionality plus the auto-scanning functionality.

For more information on how this generally works, read Configuring Beans in Spring Framework

The View Resolver configured above specifies how Spring should locate the view files: the V in MVC. In our example, it tells Spring to look for files within /WEB-INF/views/ directory which ends with .jsp Such a file, say index.jsp may look thus:

<html>
<head>
    <title></title>
</head>
<body>
Hello, ${name}
</body>
</html>

Having that as the view file, a Controller file, say named Index.java can be created thus:

@Controller
@RequestMapping("/")
public class Index {

    @RequestMapping(method = RequestMethod.GET)
    public String Index(ModelMap model){
        model.addAttribute("name", "James Bond");
        return "index";
    }
}


Note the @Controller annotation.

With these all set up, you can now deploy your application and when you access http://localhost/ you should see the message: Hello, James Bond.

For a more thorough take on Spring MVC, the web section of the Spring Framework documentation is a recommended read.

No comments:

Post a Comment