Spring MVC in Maven

I have heard Spring for years but i have no chance to work with it before. Finally i could get a touch on it in year 2010. My first goal is learning the Spring MVC.

I find a very useful tutorial on building a Spring MVC application. The sample codes there use Ant for building the application.


I have followed Chapter 1 – Basic Application and Environment Setup and and created the same sample project but with Maven without using Ant.
 

*Note: I try to use Spring 3.0 in the following example

Basic Application and Environment Setup


1. Follow Maven – Create a Simple Webapp Project to create a simple webapp Maven project

2. Edit the pom.xml as follow

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>spring-mvc-trial</groupId>
	<artifactId>spring-mvc-trial</artifactId>
	<packaging>war</packaging>
	<version>1.0</version>
	<name>Spring MVC Trial</name>
	<description>Spring MVC Trial</description>

	<!-- Repositories -->
	<repositories>
		<!-- EBR Spring Release Repository -->
		<repository>
			<id>com.springsource.repository.bundles.release</id>
			<name>EBR Spring Release Repository</name>
			<url>http://repository.springsource.com/maven/bundles/release</url>
		</repository>
		<!-- EBR Spring External Repository -->
		<repository>
			<id>com.springsource.repository.bundles.external</id>
			<name>EBR External Release Repository</name>
			<url>http://repository.springsource.com/maven/bundles/external</url>
		</repository>
		<!-- EBR Spring Milestone Repository -->
		<!--repository>
			<id>com.springsource.repository.bundles.milestone</id>
			<name>EBR Spring Milestone Repository</name>
			<url>http://repository.springsource.com/maven/bundles/milestone</url>
		</repository-->
		<!-- EBR Spring Snapshot Repository -->
		<!--repository>
			<id>com.springsource.repository.bundles.snapshot</id>
			<name>EBR Spring Snapshot Repository</name>
			<url>http://repository.springsource.com/maven/bundles/snapshot</url>
		</repository-->
		<!-- Maven Central Compatible Spring Snapshot Repository -->
		<!--repository>
			<id>org.springframework.maven.snapshot</id>
			<name>Maven Central Compatible Spring Snapshot Repository</name>
			<url>http://maven.springframework.org/snapshot</url>
		</repository-->
	</repositories>
	
	<!-- Project properties -->
	<properties>
		<org.springframework.version>3.0.1.RELEASE</org.springframework.version>
	</properties>
	
	<!-- Build Configuration -->
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	
	<!-- Dependencies -->
	<dependencies>
		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>org.springframework.core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>org.springframework.web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>org.springframework.web.servlet</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<!-- Other dependencies -->
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
		</dependency>
	</dependencies>
	
</project>

 

3. Add the servlet mapping to the web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app
	version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>

	<!-- springapp servlet -->
	<servlet>
		<servlet-name>springapp</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springapp</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>

	<!-- Welcome files -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

4. Also create the springapp-servlet.xml in the WEB-INF folder

<?xml version="1.0" encoding="UTF-8"?>

<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- the application context definition for the springapp DispatcherServlet -->
	<bean name="/hello.htm" class="springapp.web.HelloController"/>
</beans>

 

5. Create the /src/main/java/springapp/web/HelloController.java

package springapp.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

public class HelloController implements Controller {

	protected final Log logger = LogFactory.getLog(getClass());

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("Returning hello view");
		System.out.println("stdout - Returning hello view");

		return new ModelAndView("hello.jsp");
	}
}

 

6. Create the /src/test/java/springapp/web/HelloControllerTest.java for unit Test

package springapp.web;

import org.springframework.web.servlet.ModelAndView;
import springapp.web.HelloController;
import junit.framework.TestCase;

public class HelloControllerTest extends TestCase {

	public void testHandleRequestView() throws Exception{		
		HelloController controller = new HelloController();
		ModelAndView modelAndView = controller.handleRequest(null, null);		
		assertEquals("hello.jsp", modelAndView.getViewName());
	}
}

 

7. Create the /src/main/webapp/hello.jsp

<head><title>Hello :: Spring Application</title></head>
<body>
	<h1>Hello - Spring Application</h1>
	<p>Greetings.</p>
</body>

 

8. The folder structure should look like this

 

9. Run Maven install to build the .war file

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Spring MVC Trial
[INFO] 
[INFO] Id: spring-mvc-trial:spring-mvc-trial:war:1.0
[INFO] task-segment: [install]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire:test]
[INFO] Surefire report directory: D:\Workspaces\spring3-trial\spring-mvc-trial\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running springapp.web.HelloControllerTest
2010/2/28 下午 11:53:35 springapp.web.HelloController handleRequest
資訊: Returning hello view
stdout - Returning hello view
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.11 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[spring-mvc-trial] in [D:\Workspaces\spring3-trial\spring-mvc-trial\target\spring-mvc-trial-1.0]
[INFO] Processing war project
[INFO] Webapp assembled in[86 msecs]
[INFO] Building war: D:\Workspaces\spring3-trial\spring-mvc-trial\target\spring-mvc-trial-1.0.war
[INFO] [install:install]
[INFO] Installing D:\Workspaces\spring3-trial\spring-mvc-trial\target\spring-mvc-trial-1.0.war to C:\Users\Administrator\.m2\repository\spring-mvc-trial\spring-mvc-trial\1.0\spring-mvc-trial-1.0.war
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4 seconds
[INFO] Finished at: Sun Feb 28 23:53:36 CST 2010
[INFO] Final Memory: 2M/12M
[INFO] ------------------------------------------------------------------------

 

10. Copy the .war file to the Tomcat webapp folder
 

11. Open the hello.htm in browser

 

12. Check the Tomcat stdout_<yyyymmdd>.log and you should find the log written by the HelloController

Done =)

Update 2010-03-31:
Add the spring framework repositories in the pom.xml. Thanks Daniele.

Update 2010-12-27:
Uncommented the EBR Spring External Repository in the pom.xml to solve the missing com.springsource.org.aopalliance-1.0.0.jar problem.

Update 2010-12-31:
It is found that the default Maven Repository also contains the springframwork libraries. So you don’t need to specify the EBR repositories in the pom.xml, just rename the dependencies as follow.

...
<!-- Spring framework -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
...

 

Thanks Alex. =)

43 thoughts on “Spring MVC in Maven”

    1. Oh, i forgot to include the spring framework repository in the pom.xml. i have added it back. Thanks Daniele. =)

      Like

  1. Well compiled article. However one needs to know here that com.springsource.org.aopalliance-1.0.0.jar needs to be manually downloaded and installed for the maven build to be successful.

    Like

    1. Hi Tomasz,

      you don’t need to download the jar manually. Maven manages all dependencies by the pom.xml when the project is built.

      Like

      1. com.springsource.org.aopalliance-1.0.0.jar is not automatically downloaded by Maven. Have the same problem – project cannot be built

        Like

      2. Hi Alex,

        It seems that the com.springsource.org.aopalliance-1.0.0.jar is stored in the external repository. Try uncommenting the EBR Spring External Repository in the pom.xml as i have updated in this post.

        Kit

        Like

  2. Also we can remove repositories in pom.xml and so that use Maven repository. We just need to slightly modify Spring artefacts:

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

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

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

    Like

  3. Thanks a lot. I have started my knowledge in spring with the help of your hello world application.

    Like

  4. Thanks for the tutorial man! It took me 10 minutes at maximum to complete it.

    Just a comment:

    If you are using tomcat, you can set a few configurations to use ‘mvn tomcat:deploy’ goal and maven does the copy for you, and you can update your webapp in runtime. It’s not directly related to this, but it might help.

    Let me know if you want it and I’ll send it to you.

    Again, very nice tuto!!

    Like

    1. Thanks for your comment Sebastian. =)
      I haven’t done any Java development in the recent half year. Let me ask you for that if i need it later. =P

      Like

  5. FYI: Little typo:

    6. Create the /src/main/java/springapp/web/HelloControllerTest.java for unit Test

    You actually intended for this to go into /src/test/java… The screenshot of the directory structure shows the test file in the correct location, however.

    Like

  6. can i what should i write in index.jsp? when i run this program directly in server i get only index page? i donno where to redirect it..

    Like

    1. so you mean u only have the index.jsp working?
      what happen if you access hello.htm?

      And did you run it with the maven-jetty–plugin or u deploy the webapp to a tomcat server?

      Like

  7. A very good tutorial for Spring MVC in Maven. Finally, I reached the end of the “Developing a Spring Framework MVC application step-by-step”.
    Here are the most important issues:
    1. Put jdbc.properties, messages.properties and test-context.xml under src/main/resources directory. Put db directory under springapp directory.
    2. Use the following pom.xml:

    ......
    <!-- Dependencies required in Chapter 2 -->
    <dependency>
       	<groupId>javax.servlet</groupId>
    	<artifactId>jstl</artifactId>
    	<version>1.2</version>
    </dependency>
    <dependency>
    	<groupId>taglibs</groupId>
    	<artifactId>standard</artifactId>
    	<version>1.1.2</version>
    </dependency>
    
    <!-- Dependencies required in Chapter 5 -->
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-jdbc</artifactId>
    	<version>${org.springframework.version}</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-test</artifactId>
    	<version>${org.springframework.version}</version>
    </dependency>
    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate</artifactId>
    	<version>3.2.4.ga</version>
    </dependency>
    <dependency>
    	<groupId>hsqldb</groupId>
    	<artifactId>hsqldb</artifactId>
    	<version>1.8.0.10</version>
    </dependency>
    
    <!-- Dependencies required in Chapter 6 -->
    <dependency>
    			<groupId>commons-dbcp</groupId>
    			<artifactId>commons-dbcp</artifactId>
    			<version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.12</version>
    </dependency>
    ......
    

    Like

    1. Hi Toe,

      Thanks for your comment. but if you wanna post a piece of code, please wrap it with the “sourcecode” syntax.

      you can refer to Syntax Highlight for more information or you can send me the pom.xml and i update your comment. thanks.

      Kit

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.