Setting up a spring mvc project with maven in eclipse

Setting up a new spring project for eclipse with maven is a very straight forward and easy task. In case for those wondering why to use maven, well, I will just suggest reading this page http://maven.apache.org/benefits-of-using-maven.html where almost all pros mentioned are true.

In this article we will create a ready for development spring mvc project that will also include the junit testing environment. I’m not going to give many details just a basic idea of how we can accomplish this with the eclipse.

Basic understanding of eclipse usage and of maven is required to understand this article.
Now, first of all you will need an existing jee eclipse (I use Indigo, 3.7 ) with the maven plugin installed and the spring tools installed (not required but would be very nice to have). For those NOT knowing how to have the previous requirements ready do the following:

1. Download the jee eclipse indigo from here: http://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/indigosr1

Install and start.

2. Go to eclipse marketplace (Help->Eclipse Marketplace). Search for the ‘Maven Integration for Eclipse WTP’ , if can’t find it just type maven in find field and hit go. A list of plugins related to maven will appear. Find the Maven Integration for Eclipse WTP , and click install.
Let the plugin installed appropriately, restart when prompt and complete.

3. If desired, install from the Eclipse Marketplace the spring tools as well.
Open Eclipse Marketplace (Help->Eclipse Marketplace) and install . To find this plugin you may search for spring and it should be the first plugin in the search results. Install completely – restart when prompt – and you are ready to go.

Our environment is ready to create the project. Before even opening the eclipse – if it is open is ok, but we won’t be doing anything in eclipse yet – we will create our basic structure for our project. I myself like to have the following structure for my project:

[project] ->src -> main -> java — folder for the source code
[project] ->src -> main -> resources — folder for the resources, xmls, property files etc….
[project] -> src -> main ->webapp — the root folder for the web application, will conteain the web content, pages, css, javascript files etc… and the web-inf folder
[project]->src-> test -> java -– The folder for the test source – junit test classes and anything related to junit testing
[project]->src-> test -> resources – The folder which will contain all resources for our tests.

Now, there are two ways to proceed. To create a new maven project in eclipse and use the previous structure on the way, OR to create the structures in the file system along with the pom of the project and import the project in the eclipse. I will show you the second approach.
We create the previous structure in the file system – inside the eclipse workspace and in the root folder we will create a pom.xml. Pom must look like the following:

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>springtest</groupId>
  <artifactId>springTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
     
  <name>Our Spring test project</name>
  <properties>
        <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
        <javax.servlet.jstl.version>1.2</javax.servlet.jstl.version>
    </properties>
    
  <dependencies>
       <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
       </dependency>
       

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</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-test</artifactId>
            <version>${org.springframework.version}</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${javax.servlet.jstl.version}</version>
        </dependency>
	   <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
	   
	   <dependency>
	     <groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.8.1</version>
		<scope>test</scope>
	   </dependency>
  </dependencies>
 
  <build>
 
    <plugins>
 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF8</encoding>
                </configuration>
                <inherited>true</inherited>
            </plugin>
            
    </plugins>
	
	
	<resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
            <testResource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
  </build>
</project>

This is all that we ‘ll be needing for the project. Notice the properties which reflect the versions of spring framework and the jstl. This is handy if you want latter on to upgrade your project with the newer versions. I’m not going to explain in detail what all the content means. If you do not understand you should read documentation about maven!

Now we are ready to create the eclipse project. We open eclipse and choose:
Import -> Maven -> Existing Maven projects

Next in the import wizard we point to the springTest folder and proceed to finish the wizard.
We are almost ready. The only thing that is needed right now is to add to our project a web facet.
Before adding a web facet we create a server in the server view. Any server we’ll do. I myself use jboss and tomcat.

In project Facets we click on the Dynamic Web module (should be checked) choose version 2.5 and from below we click on the further configuration available link we choose springTest as context root and set Content directory to:
Content Directory: /src/main/webapp
This step is important. If we don’t set content directory to /src/main/webapp then the eclipse will create an additional folder in our project named WebContent.
Also, click on runtimes on the right side of the panel and click runtimes, and choose the server created in previous step.

When finished (after hitting apply) the eclipse will have created a WEB-INF folder inside webapp and a web.xml file, which is our jee web xml file.
Alter web.xml content to the following

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>springTest</display-name>
 
  <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>*.html</url-pattern>
  </servlet-mapping>
</web-app>

Create an xml file named springapp-servlet.xml inside the WEB-INF folder put the following content:

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

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

  <!-- the application context definition for the springapp DispatcherServlet -->
		<!-- Scans within the base package of the application for @Components to 
		configure as beans -->
	<!-- @Controller, @Service, @Configuration, etc. -->
	<context:component-scan base-package="springtest" />
	
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

In the spring beans xml: We set base path springiest to look for controllers so everything inside springiest package annotated with @Controller will be added in controllers (we will create one in few will). All spring views should appear in a folder named asp inside WEB-INF (see below).

In order to test if spring works we’ll create a controller and a jsp file.
Create a class named springtest.controllers.HelloController inside the src/main/java source folder

package springtest.controllers;


import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;


@Controller
public class HelloController {
    protected final Logger logger = Logger.getLogger(getClass());

    @RequestMapping("/hello.html")
    public String handleRequest(Model model) {

        logger.debug("Returning index view");
        model.addAttribute("message", "HELLO!!!");
        return "hello";
    }
}

Create an index.jsp inside the webapp folder. The index.jsp should look like the following:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% response.sendRedirect("hello.html"); %>

Finally create a jsp folder inside the WEB-INF folder and a page named hello.jsp with the following lines:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
         prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello page</title>
</head>
<body>
	<c:out value="${requestScope.message}"/>
</body>
</html>

Now you are ready to start and test the application.
If you start in tomcat and hit in browser: http://localhost:8080/springTest
You should see the following in the browser:
HELLO!!!
This means that spring is working properly.

Application first called index.jsp which redirected to hello.html which, through spring served by our controller and ended up in asp/hello.jsp.

Enjoy!
gred

About these ads

10 thoughts on “Setting up a spring mvc project with maven in eclipse

  1. First of all thanks for the tutorial. Unfortunately I get stuck at the point where the dynamic web module must be configured. The link ” Further configuration available” does not show up in my Eclipse version (Juno SR1). Any suggestions?

    • If you are just interested in starting right away I would suggest you to install the spring source tools plugin ( or the whole spring source ide with the tools installed, found here http://www.springsource.org/downloads/sts-ggts ) and create a new project as follows:
      Select Create New Project, from the ‘SpringSource Tool Suite’ folder select Spring Template Project, click Next and from the templates choose Spring MVC project and everything will be created for you. Then just create a server inside the eclipse load the project and run.

      If still you like to do the whole thing on your own like I describe it in this article let me know and I will help you out!

  2. Thanks for the tutorial.
    But I am doing something wrong. I still end up with the message in the browser

    “Error 404 – Not Found

    No context on this server matched or handled this request.
    Contexts known to this server are:”

    Any help will be appreciated

    • To verify the context root right click on the project in the package explorer and select Web Project Settings. In there you will find the context root.
      Use this context root in your browser. E.g. if context root = springTest then use: http://localhost:8080/sprintTest.
      If you still get a 404 error verify that you have loaded the web app on the server. TO verify this check on the server view in the eclipse click on the arrow left of the server and verify that below the server the springTest project is hanging.
      If NOTHING is under the server, right click on the server and choose Add Remove.
      In the popup window select the springTest from the left pool, the Available, and click on Add > button and then click finish and start the server and try again.

  3. Hi, I’m running the tutorial but stumbles on “In project Facets we click on the Dynamic Web module (should be checked)”. What is project facets?! It’s my first Maven project in Eclipse.

    CH

    • Marisa, I’m not sure I understand your question. I got no recommendation to write this article. What do you mean by that?

  4. Hey There. I found your blog using msn. This is a very well written article.
    I will make sure to bookmark it and come back to read more of your useful info.

    Thanks for the post. I’ll certainly return.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s