Book Image

Spring MVC Cookbook

By : Alexandre Bretet, Alex Bretet
Book Image

Spring MVC Cookbook

By: Alexandre Bretet, Alex Bretet

Overview of this book

Spring MVC is a lightweight application framework that comes with a great configuration by default. Being part of the Spring Framework, it naturally extended and supported it with an amazing set of recognizable annotations. External libraries can be plugged in and plugged out. It also possesses a request flow. Complete support of REST web services makes the Spring architecture an extremely consistent choice to support your front-end needs and Internet transformations. From the design of your Maven modules, you will achieve an Enterprise-standard for a stateless REST application based on Spring and Spring MVC with this book. This guide is unique in its style as it features a massive overview of practical development techniques brought together from the Spring ecosystem, the new JEE standards, the JavaScript revolution and Internet of Things. You will begin with the very first steps of Spring MVC's product design. Focused on deployment, viability, and maintainability, you will learn the use of Eclipse, Maven, and Git. You will walk through the separation of concerns driven by the microservices principles. Using Bootstrap and AngularJS, you will develop a responsive front-end, capable of interacting autonomously with a REST API. Later in the book, you will setup the Java Persistence API (JPA) within Spring; learn how to configure your Entities to reflect your domain needs, and discover Spring Data repositories. You will analyze how Spring MVC responds to complex HTTP requests. You will implement Hypermedia and HATEOAS to guide your customer's stateless conversation with the product and see how a messaging-service based on WebSocket can be configured. Finally you will learn how to set up and organize different levels of automated-tests, including logging and monitoring.
Table of Contents (16 chapters)
Spring MVC Cookbook
About the Author
About the Reviewer


Welcome to the singular universe of Spring MVC Cookbook. We hope you are ready for this journey that will take you through modern Spring web development practices. We have been building the , a stock exchange platform with social capabilities. We are about to take you through each step of its development process.

What this book covers

Chapter 1, Setup Routine for an Enterprise Spring Application, introduces a set of practices that are standard in the industry. From the configuration of an Eclipse IDE for optimized support of Java 8, Tomcat 8, GIT and Maven, to a proper understanding of Maven as a build automation tool and as a dependency management tool, you will learn how to deploy the Spring Framework on a sustainable base in this chapter.

Whether a project is meant to become a massively profitable product or to remain a rewarding experience, it should always begin with the same Enterprise-level patterns.

This chapter is more than a guide through the first development stage of the book's application, Cloud Street Market. A bunch of standard practices are presented here as a routine for developers toward enterprise Spring applications.

Chapter 2, Designing a Microservice Architecture with Spring MVC, is a slightly longer chapter. It covers the core principles of Spring MVC, such as its request flow or the central role of DispatcherServlet. It is also about learning how to configure Spring MVC controllers and controller method-handlers with an extended source of information related to a controller's annotations.

In the path of a Microservice architecture, we install Spring and Spring MVC across modules and web projects to build functional units that are easy to deploy and easy to scale. In this perspective, we are going to shape our application with a web module that is responsible for serving a Twitter Bootstrap template along with another web module specialized in REST Web Services.

In this chapter, you also will learn how to transfer the model from controllers to JSP views using the JSTL and how to design a JavaScript MVC pattern with AngularJS.

Chapter 3, Working with Java Persistence and Entities, gives you a glimpse of . It is necessary at this stage to learn how persistent data can be handled in a Spring ecosystem and thus in a Spring MVC application. We will see how to configure, a JPA persistence provider (Hibernate) from dataSource and entityManagerFactory in Spring. You will learn how to build a beneficial JPA object-relational mapping from EJB3 Entities and then how to query repositories using Spring Data JPA.

Chapter 4, Building a REST API for a Stateless Architecture, provides insights into Spring MVC as a REST Web Services engine. We will see the amazing support the Framework provides, with several annotations acting as doorknobs on method-handlers to abstract web-related logic and thus only focus on the business. This principle appears with annotations for request binding (binding of parameters, URL paths, headers, and so on) and Response Marshalling and also for integrated support of Spring Data pagination.

This chapter also presents how to set up exception handling as part of Spring MVC to translate predefined exception-Types into generic error responses. You will understand how to configure the content negotiation, an important bit for REST APIs, and finally, how to expose and document REST Endpoints using Swagger and the Swagger UI.

Chapter 5, Authenticating with Spring MVC, presents how to configure an authentication on controllers and services from standard protocols such as HTTP BASIC and OAuth2. You will learn several concepts and practices related to Spring Security, such as the Filters chain, the <http> namespace, the Authentication Manager, or the management of roles and users. Our OAuth2 flow is a client implementation. We authenticate users in our application when they are first authenticated with a third-party provider: Yahoo! These Yahoo! authentications and connections are later used to pull fresh financial data from Yahoo! Finance. It will be very interesting to see how the OAuth2 flow can be entirely abstracted, in the backend, with the Spring Social library.

Chapter 6, Implementing HATEOAS, demonstrates how to take a RESTful Spring MVC API a step further. A Hypermedia-driven application provides links along with every single requested resource. These links reflect URLs of related resources. They provide to the user client (whatever type of client it may be) real-time navigation options—precious documentation that is also the actual implementation.

We will see how to build such links from JPA Entities associations or from the controller layer.

Chapter 7, Developing CRUD Operations and Validations, goes into the more advanced concepts of Spring MVC. Presenting the tools and techniques that support interactive HTTP methods (PUT, POST, and DELETE), we will lean on the HTTP1/1 specification (RFC 7231 Semantics and Content) to learn how to return the appropriate response status code or headers.

Our use of the Spring Validator together with the ValidationUtils utility class provides a compliant implementation of the validation-related JSR-303 and JSR-349 specifications.

The last recipe is the place where an internationalization (I18N) of messages and content happens. We also present a client-side implementation, with AngularJS, that relies on published internationalization web services.

Chapter 8, Communicating Through WebSockets and STOMP, focuses on the uprising WebSocket technology and on building Message-Oriented-Middleware for our application. This chapter provides a rare showcase that implements so much about WebSockets in Spring. From the use of the default embedded WebSocket message broker to a full-featured external broker (with STOMP and AMQP protocols), we will see how to broadcast messages to multiple clients and also how to defer the execution of time-consuming tasks with great scalability benefits.

You will learn how to dynamically create private queues and how to get authenticated clients to post and receive messages from these private queues.

To achieve a WebSocket authentication and an authentication of messages, we will make the API stateful. By stateful, understand that the API will use HTTP sessions to keep users authenticated between their requests. With the support of Spring Session and the highly clusterable Redis server, sessions will be shared across multiple web apps.

Chapter 9, Testing and Troubleshooting, introduces a set of tools and common practices to maintain, debug, and improve an application's state. As a way of finishing this journey, we will visit how to upgrade the database schema from one version of the application to another as part of the Maven builds with the Flyway Maven Plugin. We will also go through how to write and automate unit tests (with Maven Surefire and Mockito) and integration tests (using a set of libraries such as Cargo, Rest-assured, and Maven Failsafe).

The last recipe provides insightful guidelines in order to apply Log4j2 globally as a logging framework, as it is more than important to rely on a relevant logging solution to troubleshoot efficiently, whichever environment we may be on.

What you need for this book

The hardware and software list details the requirements for each chapter. Before everything, an Internet connection is necessary because many external references will be pointed out as links (URLs) and software will need to be downloaded.

Also, and even more importantly, you will see that we use the Git versioning system to manage (and work from) the codebase for each chapter. Your local Git repository will correspond to the remote repository for the project (on GitHub), and you will be required to reach out to this remote repository.

To rephrase the hardware and software list, we will support three operating systems throughout the book: MS Windows, Linux, and Mac OS X.

For hardware, we recommend a modern, well-equipped workstation with at least 2 GB of RAM and 500 MB of free space on the hard drive.

Who this book is for

While writing this book, one of our objectives has been to remain as approachable as possible while providing the widest possible overview of modern web development practices.

We believed that most of you, with an interest in a cookbook about Spring MVC, are primarily looking for a starter kit and a toolbox to develop modern Spring-based web applications.

We also believed that most of you would tend to prefer conceptualizing from experience and not from theory. Nowadays, it is clear that people have different mindsets and learning preferences.

Under this light, chapters will have increasing exigence levels one after the other, from the intuitive Chapter 1, Setup Routine for an Enterprise Spring Application, to the more challenging Chapter 8, Communicating Through WebSockets and STOMP. The initial few chapters will definitely suit a broader audience of Java developers than the final ones.

Having said this, we have everything in this book! The prerequisites here are mostly pointing to external sources of information. And our showcase application is running and waiting for you to dive into it and understand how things work.

More generally, we assume you to be a Java developer with prior web experience. Beyond everything, we expect you to have a motivated interest in learning Spring web technologies.


In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We are going to review the configuration changes applied to the cloudstreetmarket-api webapp in order to set up a type conversion".

A block of code is set as follows:

<bean id="conversionService" class="">
  <property name="converters">
      <bean class="edu.zc.csm.core. converters.StringToStockProduct"/>

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Then select Add and Remove… from the right-click menu."


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

The showcase application: CloudStreet Market

We enjoyed building CloudStreet Market for you. It will remain an OpenSource GPL v3 piece of software. will serve to directly or indirectly promote the book.

The master branch will probably continue to evolve but the chapters' branches will always match the book.

Feel absolutely free to fork the repository for whichever reason you might have. We also welcome Pull Requests, if you feel things could be made differently. Also, a big amount of tests are yet to be added.

The Git repository is hosted on GitHub at the following address:

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.