Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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
€29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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
Table of content icon View table of contents Preview book icon Preview Book

Spring MVC Beginner's Guide

Chapter 2. Spring MVC Architecture – Architecting Your Web Store

What we saw in the first chapter is nothing but a glimpse of Spring MVC; in the previous chapter, our total focus was just on getting it to run a Spring MVC application. Now, it's time for us to deep-dive into Spring MVC architecture.

By the end of this chapter, you will have a clear understanding of:

  • The dispatcher servlet and request mapping
  • The web application context and configuration
  • The Spring MVC request flow and Web MVC
  • The web application architecture

The dispatcher servlet

In the first chapter, we were introduced to the dispatcher servlet and saw how to define a dispatcher servlet in web.xml. We learned that every web request first comes to the dispatcher servlet. The dispatcher servlet is the one that decides the controller method that it should dispatch the web request to. In the previous chapter, we created a welcome page that will be shown whenever we enter the URL http://localhost:8080/webstore/ on the browser. Mapping a URL to the appropriate controller method is the primary duty of a dispatcher servlet.

So the dispatcher servlet reads the web request URL and finds the appropriate controller method that can serve that web request and invokes it. This process of mapping a web request to a specific controller method is called request mapping, and the dispatcher servlet is able to do this with the help of the @RequestMapping annotation (org.springframework.web.bind.annotation.RequestMapping).

Time for action – examining request mapping

Let's observe what will happen when you change the value attribute of the @RequestMapping annotation by executing the following steps:

  1. Open your STS and run the webstore project; just right-click on your project and choose Run As | Run on Server. You will be able to view the same welcome message on the browser.
  2. Now, go to the address bar of the browser and enter the URL, http://localhost:8080/webstore/welcome.
  3. You will see the HTTP Status 404 error page on the browser, and you will also see the following warning in the console:
    WARNING: No mapping found for HTTP request with URI [/webstore/welcome] in DispatcherServlet with name ' DefaultServlet'
    
    Time for action – examining request mapping

    An error log displaying the "No mapping found" warning message

  4. Now, open the HomeController class, change the @RequestMapping annotation's value attribute to /welcome, and save it. Basically, your new request mapping annotation will look like @RequestMapping("/welcome...

The web application context

In a Spring-based application, our application objects live within an object container. This container creates objects and associations between objects, and manages their complete life cycle. These container objects are called Spring-managed beans (or simply beans), and the container is called an application context in the Spring world.

A Spring container uses dependency injection (DI) to manage the beans that make up an application. An application context (org.springframework.context.ApplicationContext) creates beans and associate beans together based on the bean configuration and dispenses beans on request. A bean configuration can be defined via an XML file, annotation, or even via Java configuration classes. We will use only XML- and annotation-based bean configurations in our chapters.

A web application context is the extension of an application context, designed to work with the standard servlet context (javax.servlet.ServletContext). A web application context...

Time for action – understanding the web application context

You have received enough of an introduction on the web application context; now, tweak a little bit with the name and location of the web application context configuration file (DefaultServlet-servlet.xml) and observe the effect. Perform the following steps:

  1. Rename the DefaultServlet-servlet.xml file to DispatcherServlet-servlet.xml; you can find DefaultServlet-servlet.xml under the src/main/webapp/WEB-INF/ directory.
  2. Then, run your webstore project again and enter the URL, http://localhost:8080/webstore/; you will see an HTTP Status 500 error message on your web page and a FileNotFoundException error in the stack trace as follows:
    java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/DefaultServlet-servlet.xml]
    
    Time for action – understanding the web application context

    An error message displaying FileNotFoundException for DefaultServlet-servlet.xml

  3. To fix this error, change the name of DefaultServlet to DispatcherServlet in web.xml; basically, after changing...

The web application context configuration

The web application context configuration file (DispatcherServlet-context.xml) is nothing but a simple Spring bean configuration file. Spring will create beans (objects) for every bean definition mentioned in this file during bootup of our application. If you open this web application context configuration file (/WEB-INF/spring/webcontext/DispatcherServlet-context.xml), you will find some configuration and bean definition as follows:

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

View resolvers

We saw the purpose of the first two tags that are specified within the web application context configuration file:

<mvc:annotation-driven />
<context:component-scan base-package="com.packt.webstore" />

Based on these tags, Spring creates the necessary beans to handle a web request and also creates beans for all the @Controller classes. However, to run a Spring MVC application successfully, Spring needs one more bean; this bean is called a view resolver.

A view resolver helps the dispatcher servlet identify the views that have to be rendered as the response for a specific web request. Spring MVC provides various view resolver implementations to identify views, and InternalResourceViewResolver is one such implementation. The final tag in the web application context configuration is the bean definition for the InternalResourceViewResolver class as follows:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property...

The dispatcher servlet


In the first chapter, we were introduced to the dispatcher servlet and saw how to define a dispatcher servlet in web.xml. We learned that every web request first comes to the dispatcher servlet. The dispatcher servlet is the one that decides the controller method that it should dispatch the web request to. In the previous chapter, we created a welcome page that will be shown whenever we enter the URL http://localhost:8080/webstore/ on the browser. Mapping a URL to the appropriate controller method is the primary duty of a dispatcher servlet.

So the dispatcher servlet reads the web request URL and finds the appropriate controller method that can serve that web request and invokes it. This process of mapping a web request to a specific controller method is called request mapping, and the dispatcher servlet is able to do this with the help of the @RequestMapping annotation (org.springframework.web.bind.annotation.RequestMapping).

Time for action – examining request mapping


Let's observe what will happen when you change the value attribute of the @RequestMapping annotation by executing the following steps:

  1. Open your STS and run the webstore project; just right-click on your project and choose Run As | Run on Server. You will be able to view the same welcome message on the browser.

  2. Now, go to the address bar of the browser and enter the URL, http://localhost:8080/webstore/welcome.

  3. You will see the HTTP Status 404 error page on the browser, and you will also see the following warning in the console:

    WARNING: No mapping found for HTTP request with URI [/webstore/welcome] in DispatcherServlet with name ' DefaultServlet'
    

    An error log displaying the "No mapping found" warning message

  4. Now, open the HomeController class, change the @RequestMapping annotation's value attribute to /welcome, and save it. Basically, your new request mapping annotation will look like @RequestMapping("/welcome").

  5. Again, run the application and enter...

The web application context


In a Spring-based application, our application objects live within an object container. This container creates objects and associations between objects, and manages their complete life cycle. These container objects are called Spring-managed beans (or simply beans), and the container is called an application context in the Spring world.

A Spring container uses dependency injection (DI) to manage the beans that make up an application. An application context (org.springframework.context.ApplicationContext) creates beans and associate beans together based on the bean configuration and dispenses beans on request. A bean configuration can be defined via an XML file, annotation, or even via Java configuration classes. We will use only XML- and annotation-based bean configurations in our chapters.

A web application context is the extension of an application context, designed to work with the standard servlet context (javax.servlet.ServletContext). A web application context...

Time for action – understanding the web application context


You have received enough of an introduction on the web application context; now, tweak a little bit with the name and location of the web application context configuration file (DefaultServlet-servlet.xml) and observe the effect. Perform the following steps:

  1. Rename the DefaultServlet-servlet.xml file to DispatcherServlet-servlet.xml; you can find DefaultServlet-servlet.xml under the src/main/webapp/WEB-INF/ directory.

  2. Then, run your webstore project again and enter the URL, http://localhost:8080/webstore/; you will see an HTTP Status 500 error message on your web page and a FileNotFoundException error in the stack trace as follows:

    java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/DefaultServlet-servlet.xml]
    

    An error message displaying FileNotFoundException for DefaultServlet-servlet.xml

  3. To fix this error, change the name of DefaultServlet to DispatcherServlet in web.xml; basically, after changing the...

The web application context configuration


The web application context configuration file (DispatcherServlet-context.xml) is nothing but a simple Spring bean configuration file. Spring will create beans (objects) for every bean definition mentioned in this file during bootup of our application. If you open this web application context configuration file (/WEB-INF/spring/webcontext/DispatcherServlet-context.xml), you will find some configuration and bean definition as follows:

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

View resolvers


We saw the purpose of the first two tags that are specified within the web application context configuration file:

<mvc:annotation-driven />
<context:component-scan base-package="com.packt.webstore" />

Based on these tags, Spring creates the necessary beans to handle a web request and also creates beans for all the @Controller classes. However, to run a Spring MVC application successfully, Spring needs one more bean; this bean is called a view resolver.

A view resolver helps the dispatcher servlet identify the views that have to be rendered as the response for a specific web request. Spring MVC provides various view resolver implementations to identify views, and InternalResourceViewResolver is one such implementation. The final tag in the web application context configuration is the bean definition for the InternalResourceViewResolver class as follows:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix...

Time for action – understanding InternalResourceViewResolver


We instruct Spring to create a bean for an InternalResourceViewResolver class, but why? Who is going to use this bean? What is the role of the InternalResourceViewResolver bean in Spring MVC? Find the answer to these questions through the following exercise:

  1. Open DispatcherServlet-context.xml; you can find this file under the src/main/webapp/WEB-INF/spring/webcontext/ directory in your project.

  2. Change the prefix property value of the InternalResourceViewResolver bean as follows:

    <property name="prefix" value="/WEB-INF/views/" />
  3. Now, run your webstore project again and enter the URL http://localhost:8080/webstore/. You will see an HTTP Status 404 error message in your browser as shown in the following screenshot:

    An error page displaying the no resource found message

  4. Then, rename the jsp directory (/src/main/webapp/WEB-INF/jsp) to views.

  5. Finally, run your application and enter the URL, http://localhost:8080/webstore/. You will see...

Model View Controller


So far, we have seen lots of concepts, such as the dispatcher servlet, request mapping, controllers, and view resolver; it would be good to see the overall picture of the Spring MVC request flow so that we can understand each component's responsibilities. However, before that, we need to understand the Model View Controller (MVC) concept some more. Every enterprise-level application's presentation layer can logically be divided into the following three major parts:

  • The part that manages the data (Model)

  • The part that creates the user interface and screens (View)

  • The part that handles interactions between the user, user interface, and data (Controller)

The following diagram will help you understand the event flow and command flow within an MVC pattern:

The classic MVC pattern

Whenever a user interacts with the view by clicking on a link or button, the view issues an event notification to the controller, and the controller issues a command notification to the model to update...

An overview of the Spring MVC request flow


The main entry point for a web request in a Spring MVC application is via the dispatcher servlet. The dispatcher servlet acts as the front controller and dispatches the requests to the other controller. The front controller's main duty is to find the appropriate controller to hand over the request for further processing. The following diagram shows an overview of the request flow in a Spring MVC application:

The Spring MVC request flow

Now, let's review the Spring MVC request flow in short:

  1. When we enter a URL in the browser, the request comes to the dispatcher servlet. The dispatcher servlet then acts as a centralized entry point to the web application.

  2. The dispatcher servlet determines a suitable controller that is capable of handling the request and dispatching this request to the controller.

  3. The controller method updates objects in the model and returns the logical view name and updated model to the dispatcher servlet.

  4. The dispatcher servlet consults...

The web application architecture


Now, we understand the overall request flow and responsibility of each component in a typical Spring MVC application. However, this is not enough for us to build an online web store application. We also need to know the best practices to develop an enterprise-level web application. One of the best practices in a typical web application is to organize source code into layers, which will improve reusability and loose coupling. A typical web application normally has four layers: the presentation, domain, services, and persistence. So far, whatever we have seen, such as the dispatcher servlet, controllers, view resolvers, and so on, is considered a part of the presentation layer components. Let's understand the remaining layers and components one by one.

The domain layer


Let's start with the domain layer. A domain layer typically consists of a domain model. So, what is a domain model? A domain model is a representation of the data storage types required by the business logic. It describes the various domain objects (entities); their attributes, roles, and relationships; plus the constraints that govern the problem domain. Take a look at the following domain model diagram for order processing to get a quick idea about the domain model:

Sample domain model

Each block in the preceding diagram represents a business entity, and the lines represent the associations between the entities. Based on the preceding domain model diagram, we can understand that, in an order processing domain, a customer can have many orders, each order can have many order items, and each order item represents a single product.

During coding, the domain model will be converted into corresponding domain objects and associations by a developer. A domain object is a logical...

Time for action – creating a domain object


So far, in your webstore, you have showed only a welcome message. It is now time for you to show your first product on the web page. Do this by creating a domain object, as follows, to represent the product information:

  1. Create a class called Product under the com.packt.webstore.domain package in the source folder src/main/java. Now, add the following code into it:

    package com.packt.webstore.domain;
    
    import java.math.BigDecimal;
    
    public class Product {
    
      private String productId;
      private String name;
      private BigDecimal unitPrice;
      private String description;
      private String manufacturer;
      private String category;
      private long unitsInStock;
      private long unitsInOrder;
      private boolean discontinued;
    private String condition;
    
      public Product() {
        super();
    }
    
      public Product(String productId, String name, BigDecimal unitPrice) {
        this.productId = productId;
        this.name = name;
        this.unitPrice = unitPrice;
      }
    
      // add setters...
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

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 : 9781783284887
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 36.99
Spring MVC Beginner's Guide
€36.99
Total 36.99 Stars icon

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.