Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

The dispatcher-servlet.xml file contains all of your configuration for Spring MVC. So in it you will find beans such as ViewHandlerResolvers, ConverterFactories, Interceptors and so forth. All of these beans are part of Spring MVC which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.

The application-context.xml can optionally be included when using Spring MVC or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.

These configuration files are configured in the web.xml file as shown:

Dispatcher Config

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Application Config

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

To configure controllers, annotate them with @Controller then include the following in the dispatcher-context.xml file:

<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />

Leave a Comment