Spring MVC Web Application Tutorial With Examples: Part 1

The purpose of this Spring MVC tutorial is to build a web-application utilizing the Spring MVC framework, including real world examples. This tutorial will be presented in multiple parts with each subsequent part building in more functionality such as using a Relational Database or adding use of Spring Security for authentication and authorization. The web-application we will be building is a Purchase Request Application. Some companies requires employees to submit purchase request forms in order to get approval for any company expenses/purchases. The approval process goes through several approvers for whom can approve or deny the request. A denied request can include a message from the approver on the reason for the denial which may allow the submitter the ability to make any adjustments for resubmission.  We will be making this process available as a web-application. Part 1 will demonstrate how to setup a basic Spring MVC project, create a Spring Controller, Service Layer spring components, and create a JSP template file to render the page.

Environment Details

  • JDK 1.7
  • Apache Tomcat 7
  • Maven 3.x
  • Ubuntu

Spring MVC Tutorial: Setting up Tomcat

What is Tomcat?

Apache Tomcat is an open-source web server and servlet container for rendering Java Server Pages (JSPs) and executing servlets. Web applications can be deployed to a Tomcat server using WAR files (Java web archive files). Tomcat does not support the full EE stack and will not deploy EAR files. If you don't have a place to run your Tomcat yet, you can check out JavaPipe's best Java Web Hosting offers and see if that's what you're looking for. For now let's proceed on how to setup your own Tomcat container.

Deploy your Spring MVC application on our Tomcat cloud platform. Host Your Spring MVC App in our Tomcat cloud

Installing Tomcat

  1. Download the core tar.gz file from  http://tomcat.apache.org/download-70.cgi
  2. Extract tar.gz file and copy to desired directory.
 tar -xvf apache-tomcat-7x.tar.gz 

The directory used for this tutorial is the /opt directory but you can use any directory as long as it has read and write privileges for your user.

Running Tomcat

  1. Go to /opt/apache-tomcat-7.x/bin and execute startup.sh file.
  2. Verify application server is running by going to localhost:8080/ and you should see this page:

Spring MVC Tutorial

Spring MVC Tutorial: Set Up the Project

This section of the article focuses on creating the file structure and configuration files required for this Spring application.

Create the Spring project folder

Create a PurchaseRequestApp folder, in this case it was created under /home/alux/Projects but it can be put in any directory as long as you have read and write permission.

mkdir /home/alux/Projects/PurchaseRequestApp 

Create the folder structure

Create the following folder structure under the project folder (PurchaseRequestApp)

Spring MVC Example

Create a maven build file (pom.xml) at the root of the project folder. The first dependency is spring-context which provides core Spring functionality including dependency injection. The Spring MVC framework provides HTTP integration including an implementation of Spring MVC. The jstl artifact is required to be able to use jstl on JSP pages.


 <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/xsd/maven-4.0.0.xsd" > 
                 <finalName>backoffice</finalName> <!--Sets the war file name to backoffice--> 

Deployment descriptor file (web.xml).

The deployment descriptor is used by Java web applications to determine how URLs are mapped to servlets. At this point all that is needed is to map Spring's DispatcherServlet. The DispatcherServlet is responsible for invoking the correct handlers (for this application it will be a Controller) based on the incoming request URI.


 <?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"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0"> 

Spring MVC Example Configuration File: mvc-dispatcher-servlet.xml

This file contains Spring Bean definitions and other Spring Context information.By default Spring looks for a application context configuration file /WEB-INF/${servlet-name}-servlet.xml for servlets defined in web.xml. The first thing required for this file will be the <context:component-scan base-package="com.addolux"/> line which tells the application to look through the all the classes under com.addolux for Spring bean component annotations such as @Component or @Controller (which will be implemented later) and add them to the application context. Next a ViewResolver bean must be configured so that the views returned by controllers and be resolved to a JSP.


   <?xml version="1.0" encoding="UTF-8"?> 
   <beans xmlns="http://www.springframework.org/schema/beans" 
             <context:component-scan base-package="com.addolux" /> 
             <bean id="viewResolver" 
                 <property name="viewClass" 
                           value="org.springframework.web.servlet.view.JstlView" /> 
                 <property name="prefix" value="/WEB-INF/jsp/" /> 
                 <property name="suffix" value=".jsp" /> 


Create the PurchaseRequestDTO and Service Classes

At this point there is no persistence configured for this application and the service class will return dummy DTO data.


 package com.addolux.purchaserequest.dto; 
         public class PurchaseRequestDTO { 
             private String poNumber; 
             private String date; 
             private String justification; 
             public String getPoNumber() { 
                 return poNumber; 
             public void setPoNumber(String poNumber) { 
                 this.poNumber = poNumber; 
             public String getDate() { 
                 return date; 
             public void setDate(String date) { 
                 this.date = date; 
             public String getJustification() { 
                 return justification; 
             public void setJustification(String justification) { 
                 this.justification = justification; 


 package com.addolux.purchaserequest.service; 
 import com.addolux.purchaserequest.dto.PurchaseRequestDTO; 
 import java.util.List; 
 public interface PurchaseRequestService { 
    public List<PurchaseRequestDTO> getAllPurchaseRequests(); 


 package com.addolux.purchaserequest.service.impl; 
 import com.addolux.purchaserequest.dto.PurchaseRequestDTO; 
 import com.addolux.purchaserequest.service.PurchaseRequestService; 
 import java.util.ArrayList; 
 import java.util.List; 
 public class PurchaseRequestServiceImpl implements PurchaseRequestService{ 
     public List<PurchaseRequestDTO> getAllPurchaseRequests() { 
         return getDummyPurchaseRequestData(); 
     private List<PurchaseRequestDTO> getDummyPurchaseRequestData(){ 
         List<PurchaseRequestDTO> purchaseRequestDTOs = new ArrayList<PurchaseRequestDTO>(); 
     //Create dummy data here 
     return purchaseRequestDTOs; 

Add the service class to application context

To make the PurchaseRequestServiceImpl a Spring bean component it must be configured either through xml or annotations. For this application service layer components are configured through xml to centralize the configuration details though this can also be done by adding @Component to the classes.  

Add the following line to mvc-dispatcher-servlet.xml just before the beans closing tag:


 <bean id="purchaseRequestService" class="com.addolux.purchaserequest.service.impl.PurchaseRequestServiceImpl"/> 

Create the view


spring mvc tutorial

JSP (JavaServer Pages)

I have utilized a front-end framework Bootstrap to add styling to the page. See  http://getbootstrap.com  for more information.


 <!DOCTYPE html> 
         <html lang="en"> 
             <title>Purchase Requests</title> 
             <meta name="viewport" content="width=device-width, initial-scale=1"> 
             <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" > 
             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" ></script> 
             <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" ></script> 
             <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
             <jsp:useBean id="myRequestList" scope="request" type="java.util.List"/> 
         <div class="container-fluid"> 
             <div class="page-header"> 
                 <h1>Purchase Requests</h1> 
             <div class="row"> 
                 <ul class="nav nav-tabs"> 
                     <li role="presentation" class="active"><a href="#">Saved</a></li> 
                     <li role="presentation"><a href="#">Submitted</a></li> 
                     <li role="presentation"><a href="#">Approved</a></li> 
             <div class="row"> 
                 <table class="table"> 
                         <th>PO Number</th> 
                         <c:forEach items="${myRequestList}" var="request"> 

Create the Controller

To render the jsp page using dynamic PurchaseRequestData a Controller class is implemented. For the PurchaseRequestController to be able to handle requests the annotations @Controller and @RequestMapping are required. The @Controller annotation configures the class as a Spring component intended to handle HttpRequests and @RequestMapping maps the request URI to specific handler methods and classes. To be able to handle a GET request for ${domain name}/purchase-request/myRequests the appropriate @RequestMapping values need to be added to the class and the method responsible for handling the request. The PurchaseRequestServiceImpl component can be injected by using @Resource which will by default look for a component named purchaseRequestService (which was done in previous steps).


 package com.addolux.purchaserequest.controller; 
         import com.addolux.purchaserequest.service.PurchaseRequestService; 
         import org.springframework.stereotype.Controller; 
         import org.springframework.ui.Model; 
         import org.springframework.web.bind.annotation.RequestMapping; 
         import org.springframework.web.bind.annotation.RequestMethod; 
         import javax.annotation.Resource; 
         public class PurchaseRequestController { 
             private static final String MY_REQUESTS_VIEW="myRequests"; 
             private static final String MY_REQUESTS_MODEL_ATTRIBUTE="myRequestList"; 
             private PurchaseRequestService purchaseRequestService; 
             @RequestMapping(value = "/myRequests", method = RequestMethod.GET) 
             public String getMyRequests(Model model){ 
                 model.addAttribute(MY_REQUESTS_MODEL_ATTRIBUTE, purchaseRequestService.getAllPurchaseRequests()); 
                 return MY_REQUESTS_VIEW; 

Spring MVC Example: Completed Project File Structure

spring mvc example

Spring MVC Tutorial: Build and Deploy the Application

To package the project into a war file go to the root of the project directory (where the pom.xml file is) and run the package command:

 mvn clean package 

This will create a war file under the target folder. To deploy this application copy the war file into Tomcat's webapps folder.

 cp backoffice.war /opt/apache-tomcat-7.0.63/webapps/ 

View the Spring MVC Example Application

By default the context path of the application is the name of the war file so for the above war file the purchase requests page would be located at http://localhost:8080/backoffice/purchase-request/myRequests

Spring framework framework app


We have setup a Spring MVC application project from scratch developing the necessary configurations, Java classes, and JSP pages. We set up hosting for the Spring MVC framework to make our application available online. We have even demonstrated how to add model data from within the controller so that it would be available to our JSP. In the next part of our Spring MVC tutorial series we will be wiring the application to a relational database so that the same model data can added and retrieved from the database.