Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Spring MVC Beginner's Guide
Spring MVC Beginner's Guide

Spring MVC Beginner's Guide: Your ultimate guide to building a complete web application using all the capabilities of Spring MVC

eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Spring MVC Beginner's Guide

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:
    Time for action – installing JDK

    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.
    Time for action – setting up environment variables

    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:
    Time for action – installing the Maven build tool

    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:

Time for action – installing the Tomcat web server

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:
    Time for action – installing Spring Tool Suite

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

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

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

    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:
    Time for action – creating a Spring MVC project in STS

    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:
    Time for action – creating a Spring MVC project in STS

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:

What just happened?

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:
    Time for action – adding Spring jars to the project
  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:

What just happened?

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.
    Time for action – adding Java version properties in pom.xml

    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:

A jump-start to MVC

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:
    Time for action – running the project

    Configuring the default server for a Spring MVC project

  4. Now you will see a web page that will show you a welcome message.
    Time for action – running the project

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!

Left arrow icon Right arrow icon

Description

A step-by-step pragmatic approach to web application development using Spring MVC, with relevant screenshots and concise explanations. This book is aimed at helping Java developers who want to teach themselves Spring MVC, even if they have no previous experience with Spring MVC. It would be helpful to have a bit of familiarity with basic servlet programming concepts, but no prior experience is required.

What you will learn

  • Familiarize yourself with the anatomy of the Spring development environment
  • Learn about the web application architecture and Spring MVC request flow
  • Integrate bean validation and custom validation
  • Use error handling and exception resolving
  • Discover RESTbased web service development and Ajax
  • Test your web application
  • Learn how to use Tiles and Web Flow frameworks in your MVC application
Estimated delivery fee Deliver to Indonesia

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 25, 2014
Length: 304 pages
Edition : 1st
Language : English
ISBN-13 : 9781783284870
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Indonesia

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Jun 25, 2014
Length: 304 pages
Edition : 1st
Language : English
ISBN-13 : 9781783284870
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 48.99
Spring MVC Beginner's Guide
$48.99
Total $ 48.99 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Configuring a Spring Development Environment Chevron down icon Chevron up icon
2. Spring MVC Architecture – Architecting Your Web Store Chevron down icon Chevron up icon
3. Control Your Store with Controllers Chevron down icon Chevron up icon
4. Working with Spring Tag Libraries Chevron down icon Chevron up icon
5. Working with View Resolver Chevron down icon Chevron up icon
6. Intercept Your Store with Interceptor Chevron down icon Chevron up icon
7. Validate Your Products with a Validator Chevron down icon Chevron up icon
8. Give REST to Your Application with Ajax Chevron down icon Chevron up icon
9. Apache Tiles and Spring Web Flow in Action Chevron down icon Chevron up icon
10. Testing Your Application Chevron down icon Chevron up icon
A. Using the Gradle Build Tool Chevron down icon Chevron up icon
B. Pop Quiz Answers Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(30 Ratings)
5 star 56.7%
4 star 26.7%
3 star 6.7%
2 star 6.7%
1 star 3.3%
Filter icon Filter
Top Reviews

Filter reviews by




Hui Sheng Pan Oct 03, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book for beginner
Amazon Verified review Amazon
Rasmus Jensen Jan 21, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Setting out to learn Spring MVC as well as the Java language was a daunting task for me but the Spring MVC beginners guide was extremely helpful for me for a couple of reasons:- The flow is good and it takes you through just enough of what you need to know and provides you with the code you need and then explains what the code did.- The "go ahead hero" sections tasks you with implementing things on your own based on what you have learned. This was very effective in teaching as you walk through implementing real code by being given hints.- You feel like you are building a proper full stack web application with a nice UX (bootstrap etc.) which for me at least was a motivation.What i would recommend to others who are also learning the Java language as they learn Spring MVC is to have a few resources available that can help you understand the Java code from the book.Personally i used:- http://www.tutorialspoint.com/java/index.htm- Java™ How To Program (Early Objects)as well as searching stackoverflow.com whenever i encountered code i could not understand.Overall a great Spring MVC primer and i would recommend to beginners of the Java language as well - just have a few other resources handy to help you understand the Java code.
Amazon Verified review Amazon
M.T. Oct 08, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
i have been trying to find a good spring book, this book is straight forward, and explanation is very good, no beating around the bush and bore you to death with unnecessary expert info. This book also make great reference.
Amazon Verified review Amazon
Shashikant Mar 15, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good book for beginners.
Amazon Verified review Amazon
Amazon Customer May 20, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
For me, as for begginer, the book was really amazing source for to learn the Spring Framework. I have got the required minimum of information to start web development with Spring MVC. I strongly advice to be familar with Java language before start of the reading.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela