In this chapter, we are going take a look at how we can create a basic Spring MVC application. In order to develop a Spring MVC application, we need some prerequisite software and tools. First, we are going to learn how to install all the prerequisites that are required to set up our development environment so that we can start developing the application.
The setup and installation steps given here are for Windows operating systems, but don't worry, as the steps may change only slightly for other operating systems. You can always refer to the respective tools/software vendor's websites to install them in other operating systems. In this chapter, we will learn how to set up Java and configure the Maven build tool, install the Tomcat web server, install and configure the Spring tool suite, and create and run our first Spring MVC project.
We are going to use Java 7 but Java 6 or any higher version is also sufficient. Let's take a look at how we can install JDK on Windows operating systems:
Go to the Java SE download page on the Oracle website by entering the following URL in your browser: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Click on the Java platform JDK 7 download link; this will take you to the license agreement page. Accept the license agreement by selecting that option in radio button.
Now, click on the listed download link that corresponds to your Windows operating system architecture; for instance, if your operating system is of type 32 bit, click on the download link that corresponds to Windows x86. Or, if your operating system is of type 64 bit, click on the download link that corresponds to Windows x64.
Now, it will start downloading the installer. Once the download is finished, go to the downloaded directory and double-click on the installer. This will open up the following wizard window; just click on the Next button in the wizard, leaving the default options alone, and click on the Close button at the end of the wizard:
JDK installation wizard
Now you can see the installed JDK directory in the default location; in our case, the default location is
C:\Program Files\Java\jdk1.7.0_25
.
After installing JDK, we still need to perform some more configurations to use Java conveniently from any directory on our computer. By setting up the environment variables for Java in the Windows operating system, we can make the Java compiler and tools available to the entire operating system:
Navigate to Control Panel | System | Advanced system settings.
A System Properties window will appear; in this window, select the Advanced tab and click on the Environment Variables button to open the environment variables window.
Now, click on the New button in the System variables panel, enter
JAVA_HOME
as the variable name, and enter the installed JDK directory path as the variable value; in our case, this isC:\Program Files\Java\jdk1.7.0_51
. In case you do not have proper rights for the operating system, you will not be able to edit System variables; in that case, you can create theJAVA_HOME
variable under the User variables panel.Now, in the same System variables panel, double-click on the PATH variable entry; an Edit System Variable window will appear.
Setting PATH Environment variable
Edit Variable value of Path by appending the
;%JAVA_HOME%\bin
text to its existing value.Now click on the OK button.
Now we have installed Java in our computer. To verify whether our installation has been carried out correctly, open a new command window and type java –version
and press Enter; you will see the installed version of Java on the screen:
C:\>java -version java version "1.7.0_51" Java(TM) SE Runtime Environment (build 1.7.0_51-b13) Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
Building a software project typically includes some activities such as the following:
Compiling all the source code
Generating the documentation from the source code
Packaging the compiled code into a JAR or WAR archive file
Installing the packaged archives files on a server
Manually performing all these tasks is time consuming and is prone to errors. Therefore, we take the help of a build tool. A build tool is a tool that automates everything related to building a software project, from compiling to deploying.
Many build tools are available for building a Java project. We are going to use Maven 3.2.1 as our build tool. Let's take a look at how we can install Maven:
Go to Maven's download page by entering the following URL on your browser:
Click on the apache-maven-3.2.1-bin.zip download link, and start the download.
Once the download is finished, go to the downloaded directory and extract the
.zip
file into a convenient directory of your choice.Now we need to create one more environment variable, called
M2_HOME
, in a way that is similar to the way in which we createdJAVA_HOME
. Enter the extracted Maven zip directory's path as the value for theM2_HOME
environment variable.Create one more environment variable, called
M2
, with the value%M2_HOME%\bin
, as shown in the following screenshot:Setting the M2 environment variable
Finally append the
M2
variable to thePATH
environment variable as well by simply appending the;%M2%
text to thePATH
variable's value.
Now we have installed the Maven build tool in our computer. To verify whether our installation has been carried out correctly, we need to follow steps that are similar to the Java installation verification. Open a new command window, type mvn –version
, and press Enter; you will see the following details of the Maven version:
C:\>mvn -version Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T12:37:52-05:00) Maven home: C:\Program Files\apache-maven-3.2.1 Java version: 1.7.0_51, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.7.0_51\jre Default locale: en_SG, platform encoding: Cp1252 OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"
So far, we have learned how to install JDK and Maven. Using these tools, we can compile the Java source code into the .class
files and package these .class
files into the .jar
or .war
archives. However, how do we run our packaged archives? To do this, we take the help of a web server; a web server will host our packaged archives as a running application.
Apache Tomcat is a popular Java web server cum servlet container. We are going use Apache Tomcat Version 7.0. Let's take a look at how we can install the Tomcat web server:
Go to the Apache Tomcat home page using the following URL link:
Click on the Tomcat 7.0 download link, and it will take you to the download page.
Click on the 32-bit/64-bit Windows Service Installer link; it will start downloading the installer.
Once the download is finished, go to the downloaded directory and double-click on the installer; this will open up a wizard window.
Just click through the next buttons in the wizard, leaving the default options alone, and click on the Finish button at the end of the wizard. Note that before clicking on the Finish button, just ensure that you have unchecked Run Apache Tomcat checkbox.
Installing Apache Tomcat with the default option works successfully only if you have installed Java in the default location. Otherwise, you have to correctly provide the JRE path according to the location of your Java installation during the installation of Tomcat, as shown in the following screenshot:

The Java runtime selection for the Tomcat installation
We installed Java and Maven to compile and package Java source code, and we installed Tomcat to deploy and run our application. However, prior to all this, we have to write the Spring MVC code so that we can compile, package, and run the code.
We can use any simple text editor on our computer to write our code, but that won't help us much with features such as finding syntax errors as we type, autosuggesting important key words, syntax highlighting, easy navigation, and so on.
Integrated Development Environment (IDE) can help us with these features to develop the code faster and error free. We are going to use Spring Tool Suite (STS) as our IDE.
STS is the best Eclipse-powered development environment to build Spring applications. Let's take a look at how we can install STS:
Go to the STS download page at http://spring.io/tools/sts/all.
Click on the STS installer
.exe
link to download the file that corresponds to your windows operating system architecture type (32 bit or 62 bit); this will start the download of the installer. The STS stable release version at the time of writing this book is STS 3.4.0.RELEASE based on Eclipse 4.3.1.Once the download is finished, go to the downloaded directory and double-click on the installer; this will open up a wizard window.
Just click through the next buttons in the wizard, leaving the default options alone; if you want to customize the installation directory, you can specify that in the steps you perform in the wizard.
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
In step 5 of the wizard, you have to provide the JDK path; just enter the JDK path that you configured for the
JAVA_HOME
environment variable, as shown in the following screenshot:Setting the JDK path during the STS installation
We have almost installed all the tools and software required to develop a Spring MVC application, so now, we can create our Spring MVC project on STS. However, before jumping into creating a project, we need to perform a final configuration for STS.
As I already mentioned, we can use the Tomcat web server to deploy our application, but we have to inform STS about the location of the Tomcat container so that we can easily deploy our project from STS to Tomcat. Let's configure Tomcat on STS:
Open STS from the start menu option or the desktop icon.
STS will ask you to provide a workspace directory location; provide a workspace directory path as you wish and click on the OK button.
Now, STS will show you a welcome screen. Close the welcome screen and go to the menu bar and navigate to Window | preferences | Server | Runtime Environments.
You can see the available servers listed on the right-hand side; you may also see VMware vFabric tc Server listed under the available servers, which comes along with the STS installation.
Now click on the Add button to add our Tomcat web server.
A wizard window will appear; type
tomcat
in the Select the type of runtime environment: text box, and a list of available Tomcat versions will be shown. Just select Tomcat v7.0 and select the Create a new local server checkbox. Finally, click on the Next button, as shown in the following screenshot:Selecting the server type during the Tomcat configuration on STS
In the next window, click on the Browse button and locate Tomcat's installed directory, and click on the OK button. You can find Tomcat's installed directory under
C:\Program Files\Apache Software Foundation\Tomcat 7.0
if you have installed Tomcat in the default location. Then, click on the Finish button, as shown in the following screenshot:Selecting the Tomcat location during the Tomcat configuration on STS
In step 2, we provided a workspace path for STS. When you open STS for the very first time after installing STS, it will ask you to provide a workspace location. This is because when you create a project on STS, all your project files will be created under this location only.
Once we enter STS, we should inform STS where the Tomcat has been installed. Only then can STS use your Tomcat web server to deploy the project. This is also a one-time configuration; you need not perform this configuration every time you open STS. We did this by creating a new server runtime environment in step 5. Although STS might come with an internal VMware vFabric tc Server, we chose to use the Tomcat web server as our server runtime environment.
We learned how to configure Tomcat on STS. Similarly, to build our project, STS will use Maven. But we have to tell STS where Maven has been installed so that it can use the Maven installation to build our projects. Let's take a look at how we can configure Maven on STS:
Open STS if it is not already open.
On the right-hand side, you can see the Add button, to locate Maven's installation.
Click on the Add button and choose Maven's installed directory, as shown in the following screenshot:
Selecting Maven's location during the Maven configuration on STS
Now click on the OK button in the Preferences window and close it.
So far, we have learned how we can install all the prerequisite tools and software. Now we are going to develop our first Spring MVC application using STS. STS provides an easy-to-use project template. Using these templates, we can quickly create our project directory structures without many problems.
Let's create our first spring MVC project in STS:
In STS, navigate to File | New | Project; a New Project wizard window will appear.
Select Maven Project from the list and click on the Next button, as shown in the following screenshot:
Maven project's template selection
Now, a New Maven Project dialog window will appear; just select the checkbox that has the Create a simple project (skip archetype selection) caption, and click on the Next button.
The wizard will ask you to specify artifact-related information for your project; just enter Group Id as
com.packt
, Artifact Id aswebstore
. Then, select Packaging aswar
and click on the Finish button, as shown in the following screenshot:
We just created the basic project structure. Any Java project follows a certain directory structure to organize its source code and static resources. Instead of manually creating the whole directory hierarchy by ourselves, we just handed over that job to STS. By collecting some basic information about our project, such as Group Id, Artifact Id, and the Packaging style from us, it is clear that STS is smart enough to create the whole project directory structure with the help of the Maven plugin. Actually, what is happening behind the screen is that STS is internally using Maven to create the project structure.
We want our project to be deployable in any servlet container-based web server, such as Tomcat, and that's why we selected the Packaging style as war
. After executing step 4, you will see the project structure in Package Explorer, as shown in the following screenshot:

The project structure of the application
Let's take a look at how we can add the spring-related jars via the Maven configuration:
Open
pom.xml
; you can findpom.xml
under the root directory of the project itself.You will see some tabs at the bottom of the
pom.xml
file. If you do not see these tabs, then right-click onpom.xml
and select the Open With option from the context menu and choose Maven POM editor. Select the Dependencies tab and click on the Add button in the Dependencies section. Don't get confused with the Add button of the Dependencies Management section. You should choose the Add button in the left-hand side pane.A Select Dependency window will appear; enter Group Id as
org.springframework
, Artifact Id asspring-webmvc
, and Version as4.0.3.RELEASE
. Select Scope ascompile
and then click on the OK button, as shown in the following screenshot:Similarly, add the dependency for JavaServer Pages Standard Tag Library (JSTL) by clicking on the same Add button; this time, enter Group Id as
javax.servlet
, Artifact Id asjstl
, Version as1.2
, and select Scope ascompile
.Finally, add one more dependency for servlet-api; repeat the same step with Group Id as
javax.servlet
, Artifact Id asjavax.servlet-api
, and Version as3.1.0
, but this time, select Scope asprovided
and then click on the OK button.As a last step, don't forget to save the
pom.xml
file.
In the Maven world, pom.xml
(Project Object Model) is the configuration file that defines the required dependencies. While building our project, Maven will read that file and try to download the specified jars from the Maven central binary repository. You need Internet access in order to download jars from Maven's central repository. Maven uses an addressing system to locate a jar in the central repository, which consists of Group Id, Artifact Id, and Version.
Every time we add a dependency, an entry will be made within the <dependencies> </ dependencies>
tags in the pom.xml
file. For example, if you go to the pom.xml tab after finishing step 3, you will see an entry for spring-mvc
as follows within the <dependencies> </ dependencies>
tag:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.3.RELEASE</version> </dependency>
We added the dependency for spring-mvc in step 3, and in step 4, we added the dependency for JSTL. JSTL is a collection of useful JSP tags that can be used to write JSP pages easily. Finally, we need a servlet-api jar in order to use servlet-related code; this is what we added in step 5.
However, there is a little difference in the scope of the servlet-api dependency compared to the other two dependencies. We only need servlet-api while compiling our project. While packaging our project as war
, we don't want to the ship servlet-api jar as part of our project. This is because the Tomcat web server would provide the servlet-api jar while deploying our project. This is why we selected the scope as provided for the servlet-api.
After finishing step 6, you will see all the dependent jars configured in your project, as shown in the following screenshot, under the Maven Dependencies library:

We added only three jars as our dependencies, but if you notice in our Maven dependency library list, you will see more than three jar entries. Can you guess why? What if our dependent jars have a dependency on other jars and so on?
For example, our spring-mvc jar is dependent on the spring-core, spring-context, and spring-aop jars, but we have not specified those jars in our pom.xml
file; this is called transitive dependencies in the Maven world. In other words, we can say that our project is transitively dependent on these jars. Maven will automatically download all these transitive dependent jars; this is the beauty of Maven. It will take care of all the dependency management automatically; we need to inform Maven only about the first level dependencies.
We successfully added all the required jars to our project, but we need to perform one small configuration in our pom.xml
file, that is, telling Maven to use Java Version 7 while building our project. How do we tell Maven to do this? Simply add two property entries in pom.xml
. Let's do this.
Open
pom.xml
. You will see some tabs at the bottom ofpom.xml
; select the Overview tab from the bottom ofpom.xml
, expand the properties accordion, and click on the Create button.Now, an Add property window will appear; enter Name as
maven.compiler.source
and Value as1.7
.Adding the Java compiler version properties to POM
Similarly, create one more property with Name as
maven.compiler.target
and Value as1.7
.Finally, save
pom.xml
.
We created our project and added all the required jars, so we are ready to code. We are going to incrementally build an online web store throughout this book, chapter by chapter. As a first step, let's create a home page in our project to welcome our customers.
Our aim is simple; when we enter the http://localhost:8080/webstore/
URL on the browser, we would like to show a welcome page that is similar to the following screenshot:

Don't worry if you are not able to understand some of the code; we are going to take a look at each concept in detail in the upcoming chapters. As of now, our aim is to have quick hands-on experience of developing a simple web page using Spring MVC.
To create and add a welcome page, we need to execute the following steps:
Create a
WEB-INF/jsp/
directory structure under thesrc/main/webapp/
directory; create a jsp view file calledwelcome.jsp
under thesrc/main/webapp/WEB-INF/jsp/
directory, and add the following code snippets into it and save it:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> <title>Welcome</title> </head> <body> <section> <div class="jumbotron"> <div class="container"> <h1> ${greeting} </h1> <p> ${tagline} </p> </div> </div> </section> </body> </html>
Create a class called
HomeController
under thecom.packt.webstore.controller
package in the source directorysrc/main/java
, and add the following code into it:package com.packt.webstore.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @RequestMapping("/") public String welcome(Model model) { model.addAttribute("greeting", "Welcome to Web Store!"); model.addAttribute("tagline", "The one and only amazing webstore"); return "welcome"; } }
In step 1, we just created a JSP view; the important thing we need to notice here is the <h1>
tag and the <p>
tag. Both the tags have some expression that is surrounded by curly braces and prefixed by the $
symbol:
<h1> ${greeting} </h1> <p> ${tagline} </p>
So, what is the meaning of ${greeting}
? It means that greeting
is a kind of variable; during the rendering of this JSP page, the value stored in the greeting
variable will be shown in the header 1 style, and similarly, the value stored in the tagline
variable will be shown as a paragraph.
So now, the next question of where we will assign values to those variables arises. This is where the controller will be of help; within the welcome
method of the HomeController
class, take a look at the following lines of code:
model.addAttribute("greeting", "Welcome to Web Store!"); model.addAttribute("tagline", "The one and only amazing web store");
You can observe that the two variable names, greeting
and tagline
, are passed as a first parameter of the addAttribute
method and the corresponding second parameter is the value for each variable. So what we are doing here is simply putting two strings, "Welcome to Web Store!"
and "The one and only amazing web store"
, into the model with their corresponding keys as greeting
and tagline
. As of now, simply consider the fact that model
is a kind of map. Folks with knowledge of servlet programming can consider the fact that model.addAttribute
works exactly like request.setAttribute
.
So, whatever value we put into the model can be retrieved from the view (jsp) using the corresponding key with the help of the ${}
placeholder expression notation.
We created a controller that can put values into the model, and we created the view that can read those values from the model. So, the model acts as an intermediate between the view and the controller; with this, we have finished all the coding part required to present the welcome page. So will we be able to run our project now? No; at this stage, if we run our project and enter the http://localhost:8080/webstore/
URL on the browser, we will get an HTTP Status 404 error. This is because we have not performed any servlet mapping yet. In a Spring MVC project, we must configure a front servlet mapping. The front servlet (sometimes called the front controller) mapping is a design pattern where all requests for a particular web application are directed to the same servlet. One such front servlet given by Spring MVC framework is the dispatcher servlet (org.springframework.web.servlet.DispatcherServlet
). We have not configured a dispatcher servlet for our project yet; this is why we get the HTTP Status 404 error.
The dispatcher servlet is what examines the incoming request URL and invokes the right corresponding controller method. In our case, the welcome
method from the HomeController
class needs to be invoked if we enter the http://localhost:8080/webstore/
URL on the browser. So let's configure the dispatcher servlet for our project:
Create
web.xml
under thesrc/main/webapp/WEB-INF/
directory in your project and enter the following content insideweb.xml
and save it:<web-app version="3.0" 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_3_0.xsd"> <servlet> <servlet-name>DefaultServlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>DefaultServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Now create one more xml file called
DefaultServlet-servlet.xml
under the samesrc/main/webapp/WEB-INF/
directory and enter the following content into it and save it:<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.packt.webstore" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
If you know about servlet programming, you might be quite familiar with the servlet configuration and web.xml
. In web.xml
, we configured a servlet named DefaultServlet
, which is more or less similar to any other normal servlet configuration. The only difference is that we have not created any servlet class for that configuration. Instead, the servlet class (org.springframework.web.servlet.DispatcherServlet
) is provided by the Spring MVC framework, and we make use of it in web.xml
. After this step, our configured DispatcherServlet
(DefaultServlet
) will be ready to handle any requests that come to our application on runtime and will dispatch the request to the correct controller's method.
However, DispatcherServlet
should know where our controllers and view files are located in our project, and only then can it properly dispatch the request to the correct controllers. So we have to give some hint to DispatcherServlet
to locate the controllers and view files. This is what we configured in step 2 through the DispatcherServlet-servlet.xml
file.
Don't worry if you are not able to understand each and every configuration in web.xml
and DispatcherServlet-servlet.xml
; we will take a look at these configuration files in next chapter. As of now, just remember that this is a one-time configuration that is needed to run our project successfully.
As we already configured the Tomcat web server in our STS, let's use Tomcat to deploy and run our project:
Right-click on your project from Package Explorer and navigate to Run As | Run on Server.
A server selection window will appear with all the available servers listed; just select the server that we have configured, Tomcat v7.0.
At the bottom of the window, you can see a checkbox with the caption that says Always use this server when running this project; select this checkbox and enter the Finish button, as shown in the following screenshot:
Configuring the default server for a Spring MVC project
Now you will see a web page that will show you a welcome message.
In this chapter, we saw how to install all the prerequisites that are needed to get started and run our first Spring MVC application, for example, installing JDK, the Maven build tool, the Tomcat servlet container, and STS IDE.
We also learned how to perform various configurations in our STS IDE for Maven and Tomcat, created our first Spring MVC project, and added all Spring-related dependent jars through the Maven configuration.
We had a quick hands-on experience of developing a welcome page for our web store application. During that course, we learned how to put values into a model and how to retrieve these values from the model.
Whatever we have seen so far is just a glimpse of Spring MVC, but there is much more to uncover, for example, how the model and view controller are connected to each other and how the request flow occurs. We are going to explore these topics in the next chapter, so see you there!