Home Web Development Spring MVC Beginner's Guide

Spring MVC Beginner's Guide

By Amuthan Ganeshan
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Configuring a Spring Development Environment
About this book
Publication date:
June 2014
Publisher
Packt
Pages
304
ISBN
9781783284870

 

Chapter 1. Configuring a Spring Development Environment

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.

 

Setting up Java


Obviously, the first thing that we need to do is get started with Java. The more technical name for Java is Java Development Kit (JDK). JDK includes a Java compiler (javac), a Java virtual machine, and a variety of other tools to compile and run Java programs.

 

Time for action – installing JDK


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:

  1. 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.

  2. 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.

  3. 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.

  4. 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

    Tip

    Additionally, a separate wizard also prompts you to install Java Runtime Environment (JRE). Go through that wizard as well to install JRE in your system.

  5. 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.

 

Time for action – setting up environment variables


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:

  1. Navigate to Control Panel | System | Advanced system settings.

  2. 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.

  3. 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 is C:\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 the JAVA_HOME variable under the User variables panel.

  4. 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

  5. Edit Variable value of Path by appending the ;%JAVA_HOME%\bin text to its existing value.

    Tip

    Edit the path variable carefully; you should only append the text at the end of existing value. Don't delete or disturb the existing values; make sure you haven't missed the ; (semicolon) mark as that is the first letter in the text that you will append.

  6. 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)  
 

Configuring a build tool


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.

 

Time for action – installing the Maven build tool


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:

  1. Go to Maven's download page by entering the following URL on your browser:

    http://maven.apache.org/download.cgi

  2. Click on the apache-maven-3.2.1-bin.zip download link, and start the download.

  3. Once the download is finished, go to the downloaded directory and extract the .zip file into a convenient directory of your choice.

  4. Now we need to create one more environment variable, called M2_HOME, in a way that is similar to the way in which we created JAVA_HOME. Enter the extracted Maven zip directory's path as the value for the M2_HOME environment variable.

  5. Create one more environment variable, called M2, with the value %M2_HOME%\bin, as shown in the following screenshot:

    Setting the M2 environment variable

  6. Finally append the M2 variable to the PATH environment variable as well by simply appending the;%M2% text to the PATH 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"
 

Installing a web server


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.

 

Time for action – installing the Tomcat web server


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:

  1. Go to the Apache Tomcat home page using the following URL link:

    http://tomcat.apache.org/

  2. Click on the Tomcat 7.0 download link, and it will take you to the download page.

  3. Click on the 32-bit/64-bit Windows Service Installer link; it will start downloading the installer.

  4. Once the download is finished, go to the downloaded directory and double-click on the installer; this will open up a wizard window.

  5. 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

 

Configuring a development environment


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.

 

Time for action – installing Spring Tool Suite


STS is the best Eclipse-powered development environment to build Spring applications. Let's take a look at how we can install STS:

  1. Go to the STS download page at http://spring.io/tools/sts/all.

  2. 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.

  3. Once the download is finished, go to the downloaded directory and double-click on the installer; this will open up a wizard window.

  4. 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.

  5. 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.

 

Time for action – configuring Tomcat on 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:

  1. Open STS from the start menu option or the desktop icon.

  2. STS will ask you to provide a workspace directory location; provide a workspace directory path as you wish and click on the OK button.

  3. 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.

  4. 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.

  5. Now click on the Add button to add our Tomcat web server.

  6. 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

  7. 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

What just happened?

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.

 

Time for action – configuring Maven on STS


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:

  1. Open STS if it is not already open.

  2. Navigate to Window | Preferences | Maven | Installations.

  3. On the right-hand side, you can see the Add button, to locate Maven's installation.

  4. 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

  5. Now click on the OK button in the Preferences window and close it.

 

Creating our first Spring MVC project


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.

 

Time for action – creating a Spring MVC project in STS


Let's create our first spring MVC project in STS:

  1. In STS, navigate to File | New | Project; a New Project wizard window will appear.

  2. Select Maven Project from the list and click on the Next button, as shown in the following screenshot:

    Maven project's template selection

  3. 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.

  4. The wizard will ask you to specify artifact-related information for your project; just enter Group Id as com.packt, Artifact Id as webstore. Then, select Packaging as war and click on the Finish button, as shown in the following screenshot:

What just happened?

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

Spring MVC dependencies

As we are going to use Spring MVC APIs heavily in our project, we need the Spring jars in our project during the development. As I already mentioned, Maven will take care of managing dependencies and packaging the project.

 

Time for action – adding Spring jars to the project


Let's take a look at how we can add the spring-related jars via the Maven configuration:

  1. Open pom.xml; you can find pom.xml under the root directory of the project itself.

  2. You will see some tabs at the bottom of the pom.xml file. If you do not see these tabs, then right-click on pom.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.

  3. A Select Dependency window will appear; enter Group Id as org.springframework, Artifact Id as spring-webmvc, and Version as 4.0.3.RELEASE. Select Scope as compile and then click on the OK button, as shown in the following screenshot:

  4. 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 as jstl, Version as 1.2, and select Scope as compile.

  5. Finally, add one more dependency for servlet-api; repeat the same step with Group Id as javax.servlet, Artifact Id as javax.servlet-api, and Version as 3.1.0, but this time, select Scope as provided and then click on the OK button.

  6. As a last step, don't forget to save the pom.xml file.

What just happened?

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.

 

Time for action – adding Java version properties in pom.xml


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.

  1. Open pom.xml. You will see some tabs at the bottom of pom.xml; select the Overview tab from the bottom of pom.xml, expand the properties accordion, and click on the Create button.

  2. Now, an Add property window will appear; enter Name as maven.compiler.source and Value as 1.7.

    Adding the Java compiler version properties to POM

  3. Similarly, create one more property with Name as maven.compiler.target and Value as 1.7.

  4. Finally, save pom.xml.

A jump-start to MVC

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.

 

Time for action – adding a welcome page


To create and add a welcome page, we need to execute the following steps:

  1. Create a WEB-INF/jsp/ directory structure under the src/main/webapp/ directory; create a jsp view file called welcome.jsp under the src/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>
  2. Create a class called HomeController under the com.packt.webstore.controller package in the source directory src/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";
      }
    }

What just happened?

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.

The dispatcher servlet

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.

 

Time for action – configuring the dispatcher servlet


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:

  1. Create web.xml under the src/main/webapp/WEB-INF/ directory in your project and enter the following content inside web.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>
  2. Now create one more xml file called DefaultServlet-servlet.xml under the same src/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>

What just happened?

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.

Deploying our project

We successfully created the project in the last section, so you might be curious to know what would happen if we run our project now. As our project is a web project, we need a web server to run it.

 

Time for action – running the project


As we already configured the Tomcat web server in our STS, let's use Tomcat to deploy and run our project:

  1. Right-click on your project from Package Explorer and navigate to Run As | Run on Server.

  2. A server selection window will appear with all the available servers listed; just select the server that we have configured, Tomcat v7.0.

  3. 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

  4. Now you will see a web page that will show you a welcome message.

 

Summary


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!

About the Author
  • Amuthan Ganeshan

    Amuthan Ganeshan is an experienced software professional with more than ten years of experience specializing in building distributed big data applications. He currently works as a senior software engineer at an industrial artificial intelligence software company. He is a big data enthusiast and loves sharing knowledge about software development and practices through his blog at Code Culture. He has hands on experience in developing and deploying distributed systems and has successfully delivered many steaming analytics solutions. He is also a frequent speaker in many big data conferences and authored books on enterprise Java application development.

    Browse publications by this author
Spring MVC Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now