In this post, we'll see how to get started with a Spring Web model-view-controller (MVC) framework based Hello World web application in few steps. Here, we have used m2e-wtp (Maven Integration for Eclipse WTP) to generate a web project, Eclipse IDE to develop the code and Tomcat Server 7 to deploy and run the web application which will print 'Hello World!' in the browser.

Tools,Technologies and Components used in this article

  1. Spring 3.1
  2. JDK 1.6
  3. Eclipse 3.7
  4. Maven Integration for Eclipse WTP (a.k.a m2e-wtp)
  5. Tomcat 7

Note : Spring 3 requires at least JDK 5. So, make sure you have JDK 5 or above.

Request processing workflow in Spring Web MVC

Image courtesy: springsource.org
Request processing workflow in Spring Web MVC

  1. Front Controller (DispatcherServlet) receives requests based on the url-pattern mentioned inside servlet-mapping in web.xml.
    2. Based on HandlerMapping (map of URL and Controller), Front Controller delegates the request to the matching controller.
    3. Handler method of the matching controller is responsible for processing the delegated request and returns ModeAndView to the Front Controller (DispatcherServlet).
    4. DispatcherServlet resolves the logical view name to actual view using ViewResolver and passes the Model object to the view.
    5. Response is prepared using the Model and actual view. Then the control goes back to the DispatcherServlet.
    6. DispatcherServlet returns the response which gets rendered in the browser.

1. Create a Java Web Project using m2e

Select from the menu File --> New --> Other --> Maven --> Maven Project. Browse to the workspace location and click 'Next' button.
Select project name and location

Type 'webapp' in the 'Filter' field and select archetype 'maven-archetype-webapp' to generate a simple java web application using Maven. Click 'Next' button.
Select an Archetype

Specify archetype parameters (Group Id, Artifact, Version and Package) and click 'Finish' button.
Specify Archetype parameters

2. Add Project Dependencies in pom.xml

Add dependency of Spring MVC 3 in Maven pom.xml.

File: pom.xml

<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>com.srccodes.spring</groupId>
    <artifactId>SpringMVCHelloWorld</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringMVCHelloWorld Maven Webapp</name>
    <url>http://maven.apache.org</url>
 
    <properties>
        <org.springframework.version>3.1.2.RELEASE</org.springframework.version>
    </properties>
 
    <dependencies>
        <!-- Spring MVC depends on spring-core, spring-beans, spring-context, spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
    </dependencies>
 
    <build>
        <finalName>SpringMVCHelloWorld</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Note: Spring MVC depends on spring-core, spring-beans, spring-context, spring-web. If we add 'spring-webmvc' dependency in pom.xml then all the required dependencies / libraries will be automatically downloaded and added to the project's classpath by Maven.

3. Controller Class and Request Mapping

Create a spring controller class called SpringMVCHelloController in package 'com.srccodes.spring.controller' and copy following code into it.

File: SpringMVCHelloController.java

package com.srccodes.spring.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
/**
 * @author Abhijit Ghosh
 * @version 1.0
 */
 
@Controller
public class SpringMVCHelloController {
 
    @RequestMapping("/")
    public String printHelloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
 
        return "helloWorld";
    }
}

@Controller annotation indicates that this class serves the role of a controller. The Servlet dispatcher scans @Controller annotated Controller classes for mapped handler methods and detects @RequestMapping annotations.
@RequestMapping annotation specifies that this handler method will process all requests beginning with '/' in the URL and return the logical view name.
'org.springframework.ui.Model' object is a map which is passed by the Spring container while invoking the handler method 'printHelloWorld'. The message string 'Hello World!' has been added to 'Model' object against the key 'message'. This model object is available in the view. We can use the key 'message' to get the value and display the same in the UI.

4. Create a JSP page as View

Now we need to create a JSP page called helloWorld.jsp under 'WEB-INF/pages' directory and copy the following jsp file content. We have used the key 'message' in expression '${message}' to get the value and display the same in 'helloWorld.jsp'.

File: helloWorld.jsp

<html>
<body>
<h2>${message}</h2>
</body>
</html>

5. Add Spring Configuration File

Create an xml file called dispatcher-servlet.xml under 'WEB-INF' directory and copy the following content.

File : dispatcher-servlet.xml

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
 
    <context:component-scan base-package="com.srccodes.spring.controller" />
    <mvc:annotation-driven />
     
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

The above configuration file provides context information to the Spring container. 'context:component-scan' enables the auto-detection of annotated components (like Controller, Service etc). So spring container will scan and load all the annotated component (e.g. SpringMVCHelloController) from the package 'com.srccodes.spring.controller' and it's subpackages.

'mvc:annotation-driven' specifies that we are using annotation based configuration.

ViewResolver provides a mapping between logical view name and actual view. It enables us to render models in UI without tying us to a specific view technology like JSPs, JSF, Velocity templates etc. Handler method defined in Controller class must resolve to a logical view name. In our case, 'printHelloWorld' handler method returns 'helloWorld' view name. It gets resolved to the path 'WEB-INF/pages/helloWorld.jsp' by the 'InternalResourceViewResolver' by adding prefix '/WEB-INF/pages/' and suffix '.jsp' to the view name 'helloWorld'.

6. Integrate Spring with Web Application

Copy the following content in your web.xml file.

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
 
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

DispatcherServlet (Front Controller) is mapped with the '/'. Upon initialization of the DispatcherServlet, Spring MVC looks for a configuration file called [servlet-name]-servlet.xml under the WEB-INF directory and creates the beans defined there. In our case the file is 'dispatcher-servlet.xml'.

7. Overall Project Structure

Overall Project Structure

8. Deploy and Run the Application

Right click on the project 'SpringMVCHelloWorld' and select from context menu 'Run As' --> 'Run on Server'. Select the existing tomcat server. If not available then manually define a new web server.Click "Finish" button. The web application will be deployed in the tomcat web server and a browser will be opened with 'Hello World!' message as shown below

http://localhost:8080/SpringMVCHelloWorld
Browser Output

Download SrcCodes

All code samples shown in this post are available in the following link SpringMVCHelloWorld.zip

References