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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Spring MVC Beginner's Guide
Spring MVC Beginner's Guide

Spring MVC Beginner's Guide: Unleash the power of the latest Spring MVC 4.x to develop a complete application , Second Edition

eBook
$35.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 was nothing but a glimpse of Spring MVC. Our total focus was just to get a Spring MVC application running. Now it's time for us to deep dive into the Spring MVC architecture.

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

  • The Dispatcher servlet and request mapping
  • Web application context and configuration
  • Spring MVC request flow and Web MVC
  • A typical Spring web application architecture

Dispatcher servlet

In the first chapter, we provided a little introduction to the Dispatcher servlet and you saw how to configure a Dispatcher servlet using the DispatcherServletInitializer class. You learned that every web request first comes to the Dispatcher servlet. The Dispatcher servlet is the thing that decides which controller method the web request should be dispatched to. In the previous chapter, we created a welcome page that will be shown whenever we enter the URL http://localhost:8080/webstore/ in the browser. Mapping a URL to the appropriate controller method is the primary duty of the 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 onto a specific controller method is called request mapping. And the Dispatcher servlet is able to do this with the help of the @RequestMapping (org.springframework.web.bind.annotation.RequestMapping...

Understanding the Dispatcher servlet configuration

Now we've got a basic idea of how request mapping works. I also mentioned that every web request first comes to the Dispatcher servlet, but the question is how does the Dispatcher servlet know it should handle every incoming request? The answer is we explicitly instructed it to do so through the getServletMappings method of the DispatcherServletInitializer class. Yes, when we return the string array containing only the "/" character, it indicates the DispatcherServlet configuration as the default servlet of the application. So every incoming request will be handled by DispatcherServlet.

Time for action - examining the servlet mapping

Let's observe what will happen when we change the return value of the getServletMappings method.

  1. Open DispatcherServletInitializer and change the return value of the getServletMappings method as return new String[] { "/app/*"}; basically your getServletMappings method should look...

Servlet mapping versus request mapping

The servlet mapping specifies which web container of the Java servlet should be invoked for a given URL. It maps the URL patterns to servlets. When there is a request from a client, the servlet container decides which servlet it should forward the request to based on the servlet mapping. In our case, we mapped all incoming requests to DispatcherServlet.

In contrast, request mapping guides the DispatcherServlet which controller method it needs to invoke as a response to the request based on the request path. In our case, we mapped the /welcome request path to the welcome method of the HomeController class.

Pop quiz - servlet mapping

Considering the following servlet mapping, identify the possible matching URLs:

@Override 
protected String[] getServletMappings() { 
   return new String[] { "*.do"}; 
} 
  1. http://localhost:8080/webstore/welcome
  2. http://localhost:8080/webstore/do/welcome
  3. http://localhost:8080/webstore/welcome.do
  4. http://localhost:8080/webstore...

Web application context

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

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

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

View resolvers

A view resolver helps the Dispatcher servlet to identify the views that have to be rendered as a response to a specific web request. Spring MVC provides various view resolver implementations to identify views and InternalResourceViewResolver is one such implementation:

@Bean 
public InternalResourceViewResolver getInternalResourceViewResolver() { 
    InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 
    resolver.setViewClass(JstlView.class); 
    resolver.setPrefix("/WEB-INF/jsp/"); 
    resolver.setSuffix(".jsp"); 
 
    return resolver; 
} 

Through the above bean definition is in the web application context configuration (WebApplicationContextConfig), we are instructing Spring MVC to create a bean for the class InternalResourceViewResolver (org.springframework.web.servlet.view.InternalResourceViewResolver). We will see more about the view resolver in Chapter 5, Working with View Resolver.

Time for action - understanding web...

Understanding the web application context configuration

The web application context configuration file (WebApplicationContextConfig.java) is nothing but a simple Java-based Spring bean configuration class. Spring will create beans (objects) for every bean definition mentioned in this class during the boot up of our application. If you open this web application context configuration file, you will find the following annotations on top of the class definition:

  • @Configuration: This indicates that a class declares one or more @Bean methods
  • @EnableWebMvc: Adding this annotation to an @Configuration class imports some special Spring MVC configuration
  • @ComponentScan: This specifies the base packages to scan for annotated components (beans)

The first annotation @Configuration indicates that this class declares one or more @Bean methods. If you remember, in the last section, I explained how we created a bean definition for InternalResourceViewResolver.

The second annotation is @EnableWebMvc. With this...

Dispatcher servlet


In the first chapter, we provided a little introduction to the Dispatcher servlet and you saw how to configure a Dispatcher servlet using the DispatcherServletInitializer class. You learned that every web request first comes to the Dispatcher servlet. The Dispatcher servlet is the thing that decides which controller method the web request should be dispatched to. In the previous chapter, we created a welcome page that will be shown whenever we enter the URL http://localhost:8080/webstore/ in the browser. Mapping a URL to the appropriate controller method is the primary duty of the 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 onto a specific controller method is called request mapping. And the Dispatcher servlet is able to do this with the help of the @RequestMapping (org.springframework.web.bind.annotation.RequestMapping...

Understanding the Dispatcher servlet configuration


Now we've got a basic idea of how request mapping works. I also mentioned that every web request first comes to the Dispatcher servlet, but the question is how does the Dispatcher servlet know it should handle every incoming request? The answer is we explicitly instructed it to do so through the getServletMappings method of the DispatcherServletInitializer class. Yes, when we return the string array containing only the "/" character, it indicates the DispatcherServlet configuration as the default servlet of the application. So every incoming request will be handled by DispatcherServlet.

Time for action - examining the servlet mapping

Let's observe what will happen when we change the return value of the getServletMappings method.

  1. Open DispatcherServletInitializer and change the return value of the getServletMappings method as return new String[] { "/app/*"}; basically your getServletMappings method should look like the following after your change...

Servlet mapping versus request mapping


The servlet mapping specifies which web container of the Java servlet should be invoked for a given URL. It maps the URL patterns to servlets. When there is a request from a client, the servlet container decides which servlet it should forward the request to based on the servlet mapping. In our case, we mapped all incoming requests to DispatcherServlet.

In contrast, request mapping guides the DispatcherServlet which controller method it needs to invoke as a response to the request based on the request path. In our case, we mapped the /welcome request path to the welcome method of the HomeController class.

Pop quiz - servlet mapping

Considering the following servlet mapping, identify the possible matching URLs:

@Override 
protected String[] getServletMappings() { 
   return new String[] { "*.do"}; 
} 
  1. http://localhost:8080/webstore/welcome

  2. http://localhost:8080/webstore/do/welcome

  3. http://localhost:8080/webstore/welcome.do

  4. http://localhost...

Web application context


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

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

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

View resolvers


A view resolver helps the Dispatcher servlet to identify the views that have to be rendered as a response to a specific web request. Spring MVC provides various view resolver implementations to identify views and InternalResourceViewResolver is one such implementation:

@Bean 
public InternalResourceViewResolver getInternalResourceViewResolver() { 
    InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 
    resolver.setViewClass(JstlView.class); 
    resolver.setPrefix("/WEB-INF/jsp/"); 
    resolver.setSuffix(".jsp"); 
 
    return resolver; 
} 

Through the above bean definition is in the web application context configuration (WebApplicationContextConfig), we are instructing Spring MVC to create a bean for the class InternalResourceViewResolver (org.springframework.web.servlet.view.InternalResourceViewResolver). We will see more about the view resolver in Chapter 5, Working with View Resolver.

Time for action...

Understanding the web application context configuration


The web application context configuration file (WebApplicationContextConfig.java) is nothing but a simple Java-based Spring bean configuration class. Spring will create beans (objects) for every bean definition mentioned in this class during the boot up of our application. If you open this web application context configuration file, you will find the following annotations on top of the class definition:

  • @Configuration: This indicates that a class declares one or more @Bean methods

  • @EnableWebMvc: Adding this annotation to an @Configuration class imports some special Spring MVC configuration

  • @ComponentScan: This specifies the base packages to scan for annotated components (beans)

The first annotation @Configuration indicates that this class declares one or more @Bean methods. If you remember, in the last section, I explained how we created a bean definition for InternalResourceViewResolver.

The second annotation is @EnableWebMvc. With this...

Model View Controller


So far, we have looked at lots of concepts such as the Dispatcher servlet, request mapping, controllers, and the view resolver, but it would be good to see the overall picture of the Spring MVC request flow so that we can understand each component's responsibilities. But before that, you need a basic understanding of the Model View Controller (MVC) concept. Every enterprise level application's Presentation layer can be logically divided into 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, the user interface, and the data (Controller)

The following diagram should help you to 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, or something similar, the view issues an event notification to the controller and the controller issues a command notification...

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 a front controller and dispatches the requests to the other controller. The front controller's main duty is to find the appropriate right 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

Okay, 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 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 that request to the controller.

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

  4. The Dispatcher servlet consults...

Left arrow icon Right arrow icon

Key benefits

  • Work through carefully crafted exercises with detailed explanations for each step will help you understand the concepts with ease
  • You will gain a clear understanding of the end-to-end request/response life cycle, and each logical component’s responsibility
  • This book is packed with tips and tricks that demonstrate industry best practices on developing a Spring-MVC-based application

Description

Spring MVC helps you build flexible and loosely coupled web applications. The Spring MVC Framework is architected and designed in such a way that every piece of logic and functionality is highly configurable. Also, Spring can integrate effortlessly with other popular web frameworks such as Struts, WebWork, Java Server Faces, and Tapestry. The book progressively teaches you to configure the Spring development environment, architecture, controllers, libraries, and more before moving on to developing a full web application. It begins with an introduction to the Spring development environment and architecture so you're familiar with the know-hows. From here, we move on to controllers, views, validations, Spring Tag libraries, and more. Finally, we integrate it all together to develop a web application. You'll also get to grips with testing applications for reliability.

Who is this book for?

The book is for Java developers who want to exploit Spring MVC and its features to build web applications. Some familiarity with basic servlet programming concepts would be a plus, but is not a prerequisite.

What you will learn

  • * Familiarize yourself with the anatomy of the Spring 4.X development environment
  • * Understand web application architecture and the Spring MVC request flow
  • * Integrate bean validation and custom validation
  • * Use error handling and exception resolving
  • * Get to grips with REST-based web service development and Ajax
  • * Test your web application

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Last updated date : Feb 11, 2025
Publication date : Jul 29, 2016
Length: 350 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785885648
Languages :
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Last updated date : Feb 11, 2025
Publication date : Jul 29, 2016
Length: 350 pages
Edition : 2nd
Language : English
ISBN-13 : 9781785885648
Languages :
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 $ 203.97
Spring MVC Blueprints
$54.99
Spring MVC Beginner's Guide
$48.99
Spring MVC: Designing Real-World Web Applications
$99.99
Total $ 203.97 Stars icon

Table of Contents

12 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. Internalize Your Store with Interceptor Chevron down icon Chevron up icon
7. Incorporating Spring Security Chevron down icon Chevron up icon
8. Validate Your Products with a Validator Chevron down icon Chevron up icon
9. Give REST to Your Application with Ajax Chevron down icon Chevron up icon
10. Float Your Application with Web Flow Chevron down icon Chevron up icon
11. Template with Tiles Chevron down icon Chevron up icon
12. Testing Your Application Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(16 Ratings)
5 star 62.5%
4 star 12.5%
3 star 6.3%
2 star 0%
1 star 18.8%
Filter icon Filter
Top Reviews

Filter reviews by




Amit Beriwal May 06, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
One of the rare gems. Finally helped me understand Spring MVC in simple terms. The language used is very simple and effective. Focuses on a practical approach. Highly recommended.
Amazon Verified review Amazon
David Nov 01, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book for beginners. I learned a lot of this stuff digging around the internet, I wish I would have bought this book first. It would have saved me a lot of trouble.
Amazon Verified review Amazon
George Jun 29, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Amazing how this book is organised :) , i was enjoying the book as it is a story.
Amazon Verified review Amazon
L. Figueroa Aug 04, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I decided to pick up this book after much frustration with another book. This book is excellent in the step by step instruction. There are a few (very few) minor issues but all quite obvious and will not prevent you from completing the exercises. I love the detailed explanations of everything that was used. I also found myself completing all the "Have a go Hero" exercises that required you to extend the application on your own. I had no problems at all because of the well explained steps and reasoning behind everything. I wish all my book investments were as well done as this book. I highly recommend it.
Amazon Verified review Amazon
Jean-Simon Vaillant Oct 05, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Step by Step explanations. Good examples. I was totally pleased with it.
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.

Modal Close icon
Modal Close icon