To enable Spring and Spring MVC modules in your maven project, follow the steps below
1: Add Spring related dependencies. The dependencies below will get all the rest of the transitive dependencies.
<dependency>
groupid>org.springframework</groupid>
<artifactid>spring-context</artifactid>
<version>${org.springframework.version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupid>commons-logging</groupid>
<artifactid>commons-logging</artifactid>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-webmvc</artifactid>
<version>${org.springframework.version}</version>
</dependency>
The org.springframework.version property is set to 3.0.3.RELEASE:
<org.springframework.version>3.0.3.RELEASE</org.springframework.version>
2. Setup Dispatcher Servlet in your web.xml:
The Spring MVC
requires setting the dispatcher servlet in web.xml
. Below we are loading the /WEB-INF/sprin/app-config.xml
(the main Spring application configuration file for the project) while instantiating the Dispatcher Servlet at application start up time i.e. when the server is starting up.
NOTE: You can name your application config with any name of your liking. Just make sure it is correctly referenced in Dispatcher Servlet setting in web.xml.
<servlet>
<servlet-name>springmvcdemo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvcdemo</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
3. The context config location points to the spring application config file for the application (app-config.xml).
There are 2 things of note here:
a. The com.mayabansi.webappdemo will be scanned for classes annotated with @Controller
, @Resources
, @Component
, @Service
etc.
b. The mvc-config.xml, that holds the MVC configuration settings is imported.
<!-- Scans the classpath of this application for @Components to deploy as beans -->
<context:component-scan base-package="com.mayabansi.webappdemo">
<!-- Import MVC related configuration -->
<import resource="mvc-config.xml"/>
</context:component-scan>
4. The MVC config file has Spring MVC related configuration settings:
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven>
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome">
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/">
<property name="suffix" value=".jsp">
</property>
</property>
</bean>
</mvc:view-controller>
</mvc:annotation-driven>