Configuring Spring

The Spring MVC configuration we are going to do on this page starts in web.xml, with the mapping of Spring's DispatcherServlet. The DispatcherServlet functions as a central entry point as it handles all incoming requests (or in our case the ones that conform to the url pattern that we are goign to provide). The DispatcherServlet really doesn't do much. It handles requests and passes them on to other parts of the system. This type of handling is called a front controller pattern.

Besides the DispatcherServlet we will configure a listener, that will load the Spring configuration that, in our case, will reside in application-context.xml. 

Enough intro, let's get to work.

Spring configuration in web.xml

  • Add the following to your web.xml file, on the same level as the existing <display-name> tag.




The ContextLoaderListener listener starts Spring's WebApplicationContext, which will contain the settings configured in the application-context.xml file that we will add in a minute.

The Spring DispatcherServlet is a front controller servlet. It handles all incoming Http requests (that conform to the url-pattern we provide next) and forwards them to the appropriate handlers.

The DispatcherServlet definition has an init-param called contextConfigLocation. This initialization parameter tells Spring to look for a file called application-context.xml on the classpath to find the configurations for this servlet.

Spring heavily relies on the 'the convention over configuration' principle. If we would not provide the contextConfigLocation initialization paramater, Spring would have automatically looked for a file called springDispatcherServlet-context.xml in the WEB-INF directory. That is what Spring is like. It does a lot of things "by convention", untill you override them. I prefer to have all configuration files in Maven's resources directory, that is why I have overridden Spring's convention and supplied the application-context.xml file.

The servlet-mapping tells the container (Tomcat in our case) that the DispatcherServlet is the default servlet for our application and that all URLs that don't match a different pattern should be handled by this servlet.

The 'convention over configuration' story goes for  Spring's ContextLoaderListener as well. By convention it will look for an applicationContext.xml file in the WEB-INF directory. As you know, I personally prefer calling the file application-context.xml and sticking it in the resources directory. That is why I added the <context-param> tag and again used the classpath: method to tell the ContextLoaderListener to look on the classpath for a file called application-context.xml. (Files in the resources directory will end up on the classpath)