Spring MVC: Beginner's Guide - Second Edition - Amuthan Ganeshan - E-Book

Spring MVC: Beginner's Guide - Second Edition E-Book

Amuthan Ganeshan

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Unleash the power of the latest Spring MVC 4.x to develop a complete application

About This Book

  • 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

Who This Book Is 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

In Detail

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.

Style and approach

This book takes a pragmatic step-by-step approach to web application development using Spring MVC, with informative screenshots and concise explanation.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 372

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Spring MVC Beginner's Guide - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Time for action
What just happened?
Pop quiz
Have a go hero
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book 
Errata
Piracy
Questions
1. Configuring a Spring Development Environment
Setting up Java
Time for action - installing JDK
Time for action - setting up environment variables
Configuring a build tool
Time for action - installing the Maven build tool
Installing a web server
Time for action - installing the Tomcat web server
Configuring a development environment
Time for action - installing Spring Tool Suite
Time for action - configuring Maven on STS
Time for action - configuring Tomcat on STS
Creating our first Spring MVC project
Time for action - creating a Spring MVC project in STS
Time for action - adding Java version properties in pom.xml
What just happened?
Spring MVC dependencies
Time for action - adding Spring jars to the project
What just happened?
A jump-start to MVC
Time for action - adding a welcome page
What just happened?
The Dispatcher servlet
Time for action - configuring the Dispatcher servlet
What just happened?
Deploying our project
Time for action - running the project
Summary
2. Spring MVC Architecture – Architecting Your Web Store
Dispatcher servlet
Time for action - examining request mapping
What just happened?
Pop quiz – request mapping
Understanding the Dispatcher servlet configuration
Time for action - examining the servlet mapping
What just happened?
Servlet mapping versus request mapping
Pop quiz - servlet mapping
Web application context
View resolvers
Time for action - understanding web application context
What just happened?
Understanding the web application context configuration
Pop quiz - web application context configuration
Model View Controller
Overview of the Spring MVC request flow
The web application architecture
The Domain layer
Time for action - creating a domain object
What just happened?
The Persistence layer
Time for action - creating a repository object
What just happened?
The Service layer
Time for action - creating a service object
What just happened?
Have a go hero - accessing the product domain object via a service
An overview of the web application architecture
Have a go hero - listing all our customers
Summary
3. Control Your Store with Controllers
The role of a Controller in Spring MVC
Defining a Controller
Time for action - adding class-level request mapping
What just happened?
Default request mapping method
Pop quiz - class level request mapping
Handler mapping
Using URI template patterns
Time for action - showing products based on category
What just happened?
Pop quiz - request path variable
Using matrix variables
Time for action - showing products based on filters
What just happened?
Understanding request parameters
Time for action - adding a product detail page
What just happened?
Pop quiz - the request parameter
Time for action - implementing a master detail View
What just happened?
Have a go hero - adding multiple filters to list products
Summary
4. Working with Spring Tag Libraries
The JavaServer Pages Standard Tag Library
Serving and processing forms
Time for action - serving and processing forms
What just happened?
Have a go hero - customer registration form
Customizing data binding
Time for action - whitelisting form fields for binding
What just happened?
Pop quiz - data binding
Externalizing text messages
Time for action - externalizing messages
What just happened?
Have a go hero - externalizing all the labels from all the pages
Summary
5. Working with View Resolver
Resolving Views
RedirectView
Time for action - examining RedirectView
What just happened?
Pop quiz - RedirectView
Flash attribute
Serving static resources
Time for action - serving static resources
What just happened?
Pop quiz - static view
Time for action - adding images to the product detail page
What just happened?
Multipart requests in action
Time for action - adding images to a product
What just happened?
Have a go hero - uploading product user manuals to the server
Using ContentNegotiatingViewResolver
Time for action - configuring ContentNegotiatingViewResolver
What just happened?
Working with HandlerExceptionResolver
Time for action - adding a ResponseStatus exception
What just happened?
Time for action - adding an exception handler
What just happened?
Summary
6. Internalize Your Store with Interceptor
Working with interceptors
Time for action - configuring an interceptor
What just happened?
Pop quiz - interceptors
LocaleChangeInterceptor - internationalization
Time for action - adding internationalization
What just happened?
Have a go hero - fully internationalize the product details page
Mapped interceptors
Time for action - mapped intercepting offer page requests
What just happened?
Summary
7. Incorporating Spring Security
Using Spring Security
Time for action - authenticating users based on roles
What just happened?
Pop quiz - Spring Security
Have a go hero - play with Spring Security
Summary
8. Validate Your Products with a Validator
Bean Validation
Time for action - adding Bean Validation support
What just happened?
Have a go hero - adding more validation in the Add new product page
Custom validation with JSR-303/Bean Validation
Time for action - adding Bean Validation support
What just happened?
Have a go hero - adding custom validation to a category
Spring validation
Time for action - adding Spring validation
What just happened?
Time for action - combining Spring validation and Bean Validation
What just happened?
Have a go hero - adding Spring validation to a product image
Summary
9. Give REST to Your Application with Ajax
Introduction to REST
Time for action - implementing RESTful web services
What just happened?
Time for action - consuming REST web services
What just happened?
Handling web services in Ajax
Time for action - consuming REST web services via Ajax
What just happened?
Summary
10. Float Your Application with Web Flow
Working with Spring Web Flow
Time for action - implementing the order processing service
What just happened?
Time for action - implementing the checkout flow
What just happened?
Understanding flow definitions
Understanding checkout flow
Pop quiz - web flow
Time for action - creating Views for every view state
What just happened?
Have a go hero - adding a decision state
Summary
11. Template with Tiles
Enhancing reusability through Apache Tiles
Time for action - creating Views for every View state
What just happened?
Pop quiz - Apache Tiles
Summary
12. Testing Your Application
Unit testing
Time for action - unit testing domain objects
What just happened?
Have a go hero - adding tests for Cart
Integration testing with the Spring Test context framework
Time for action - testing product validator
What just happened?
Time for action - testing product Controllers
What just happened?
Time for action - testing REST Controllers
What just happened?
Have a go hero - adding tests for the remaining REST methods
Summary
Thank you readers!
Appendix A. Using the Gradle Build Tool
Installing Gradle
The Gradle build script for your project
Understanding the Gradle script
Appendix B. Pop Quiz Answers
Chapter 2, Spring MVC Architecture - Architecting Your Web Store
Chapter 3, Control Your Store with Controllers
Chapter 4, Working with Spring Tag Libraries
Chapter 5, Working with View Resolver
Chapter 6, Internalize Your Store with Interceptor
Chapter 7, Incorporating Spring Security
Chapter 10, Float Your Application with Web Flow
Chapter 11, Template with Tiles

Spring MVC Beginner's Guide - Second Edition

Spring MVC Beginner's Guide - Second Edition

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: June 2014

Second edition: July 2016

Production reference: 1220716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-063-6

www.packtpub.com

Credits

Author

Amuthan Ganeshan

Copy Editor

Ameesha Smith-Green

Reviewer

Rafał Borowiec

Project Coordinator

Ulhas Kambali

Commissioning Editor

Nadeem Bagban

Proofreader

Safis Editing

Acquisition Editor

Vinay Argekar

Indexer

Rekha Nair

Content Development Editor

Prashanth G Rao

Production Coordinator

Melwyn Dsa

Technical Editor

Murtaza Tinwala

Cover Work

Melwyn Dsa

About the Author

Amuthan Ganeshan is a software engineer with more than nine years of experience specializing in building distributed applications. He currently works as a senior software engineer at Uptake. He is a big data enthusiast and loves sharing knowledge about software development and practices through his blog at www.codeculture.guru. He can be contacted at [email protected].

I would like to gratefully and sincerely thank Mr.Vincent Kok for his guidance, understanding, patience, and, most importantly, his friendship during my first job at Educator Inc. His mentorship has helped me to become a well-rounded professional. He encouraged me to not only grow as a developer, but also as an independent thinker.

I want to take a moment and express my gratitude to the entire team at Packt Publishing especially Murtaza Tinwala, Anish Dhurat, and Vinay Argekar, for their patience and cooperation. When I signed up for this book, I really had no idea how things would turn out. I couldn't have pulled this off without their guidance.

I would like to express my gratitude to all my friends and family for providing me with unending encouragement and support. I owe every challenge and accomplishment to all my lovely colleagues who taught me a lot over the years.

A special thanks to Divya and Arun for their encouragement, friendship, and support. They were a strong shoulder to lean on in the most difficult times during the writing of this book.

Finally, and most importantly, I would like to thank my wife Manju, who believes in me more than I do myself. Her support, encouragement, quiet patience, and unwavering love were undeniably the bedrock upon which my life has been built.

About the Reviewer

Rafał Borowiec is an IT specialist, specializing in software development, software testing and quality assurance, project management, and team leadership. He currently holds the position of a development manager at Goyello (goyello.com), where he is mainly responsible for building and managing teams of professional developers and testers.

He believes in agile project management and is a big fan of technology, especially technology that is Java-related (but not limited to this). Rafał likes sharing knowledge about software development and practices through his blog, blog.codeleak.pl , and Twitter (@kolorobot).

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

This book has a very clear aim; to introduce you to the incredible simplicity and power of Spring MVC. I still remember first learning about the Spring framework back in 2009. The best way to test whether or not you really understand a concept is to try to teach it to someone else. In my case, I have taught Spring MVC to MVC; are you confused? I mean that back in 2009, I taught it to my wife Manju Viswambaran Chandrika (MVC). During that course, I was able to understand the kind of doubts that arise in a beginner's mind. I have gathered all my teaching knowledge and put it in this book in an elegant way so that it can be understood without confusion.

It has been more than two years since the first edition of this book presented readers with a beginner-friendly way of explaining the concepts of Spring MVC. The popular reception of the book and the rapid development of the Spring MVC framework naturally demands a new edition.

In the two years since the first edition of this book was published I have received all kinds of suggestions from readers how it could be improved. With the aid of all this information I have completely revised the book. The most obvious changes in this second edition are usage of the latest and greatest versions of Spring and other libraries.

The examples in this book are completely rewritten using Spring 4.3.0.RELEASE version with Java-based configuration. Also in this edition we incorporated the popular in-memory database (HSQL DB) as our backend data-store for the example project. Though this edition includes many changes, my main audience remains the beginners.

I hope you will find this second edition more useful for learning Spring MVC thoroughly from a beginner's perspective.

What this book covers

Chapter 1, Configuring a Spring Development Environment, will give you a quick overview of Spring MVC and guide you with detailed notes of step-by-step instructions to set up your development environment. After installing the required prerequisites, you will try out a quick example of how to develop an application with Spring MVC. Although the chapter doesn’t explain all the code in detail, you’ll pick up a few things intuitively.

Chapter 2, Spring MVC Architecture – Architecting Your Web Store, lays down the ground work for the sample application that we are going to build along the way, chapter by chapter. This chapter will introduce you to concepts such as Request mapping, the web application context, Spring MVC request flow, and the layered architecture of a typical web application. You will also learn about how to set up the in-memory database for our sample application.

Chapter 3, Control Your Store with Controllers, will take you into the concept of controller; you will learn in detail about defining a controller, how to use URI Template Patterns, Matrix variables and Request parameters.

Chapter 4, Working with Spring Tag Libraries, will show you how to use Spring and Spring-form tag libraries in web form handling. You will learn how to bind the domain objects with the views. You will also learn how to use message bundles to externalize label caption texts. At the end of this chapter you will see how to add a login form.

Chapter 5, Working with View Resolver, teaches you the inner mechanics of how InternalResourceViewResolver resolves a view and take you through how to use various view types such as redirect view and static view. You will also learn about Mutipart resolver and content negotiation view resolver. Finally, you will learn how to use Exception handler resolvers.

Chapter 6, Internalize Your Store with Interceptor, presents the concept of the interceptor to you; you will learn how to leverage the interceptor to handle or transform requests and responses flexibly. This chapter will teach you how to make your webpage to support internalization with the help of LocaleChangeInterceptor. This chapter also introduces how to do audit logging in a log file using interceptor concept.

Chapter 7, Incorporating Spring Security, gives you an overview of how to incorporate Spring Security framework with Spring MVC. You will learn how to do simple authentication and authorization on a Spring MVC-based web application. 

Chapter 8, Validate Your Products with a Validator, gives you an overview of validation concept. You will learn about bean validation, and you will learn how to perform custom validation along with the standard bean validation that bean validation. You will also learn about classic Spring validation and how to combine it with bean validation.

Chapter 9, Give REST to Your Application with Ajax, teaches you the basic principles of REST and Ajax, And you will learn how to develop application in RESTful services. The basic concept of HTTP verbs and how it is related to standard CRUD operations will be explained, and you will learn how to do fire Ajax requests and how to handle them from a web page.

Chapter 10, Float Your Application with Web Flow, will show you how to use Spring web flow to develop work flow-based web pages. You will learn more about states and transitions in web flow and how to define a flow definition.

Chapter 11, Template with Tiles, teaches you how to decompose a page using Apache tiles; you will learn more about TileViewResolver and how to define reusable Apache tile templates.

Chapter 12, Testing Your Application, introduces how to leverage the Spring testing capability to test your controllers. You will learn how to load the test context and how to mock the service and repository layers. This chapter also introduces you to the Spring MVC test module and how to use it.

Appendix A, Using the Gradle Build Tool, introduces you to using the Gradle build tool for our sample application. You will learn about the Gradle script that is required to build our project using Gradle build tool.

Appendix B, Pop Quiz Answers, will provide you with the answers to the Pop quizsections in the book.

What you need for this book

To run the examples in the book the following softwares will be required:

Java SE Development KitMavenApache TomcatSpring Tool Suite

Who this book is 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.

Sections

In this book, you will find several headings that appear frequently (Time for action, What just happened?, Pop quiz, and Have a go hero).

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

Time for action

Action 1Action 2Action 3

Instructions often need some extra explanation to ensure they make sense, so they are followed by these sections.

What just happened?

This section explains the working of the tasks or instructions that you have just completed.

You will also find some other learning aids in the book.

Pop quiz

These are short multiple-choice questions intended to help you test your own understanding.

Have a go hero

These are practical challenges that give you ideas to experiment with what you have learned.

Conventions

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: "Enter the installed JDK directory path as the variable value; in our case, this would be C:\Program Files\Java\jdk1.8.0_91. "

A block of code is set as follows:

<%@ taglib prefix="c"       uri="http://java.sun.com/jsp/jstl/core"%>      <!DOCTYPE html>      <html lang="en">      <head>      <meta charset="utf-8">      <meta http-equiv="X-UA-Compatible"                content="IE=edge">      <meta name="viewport" content="width=device-width,      initial-scale=1">

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.2.RELEASE</version> </dependency>

Any command-line input or output is written as follows:

Java(TM) SE Runtime Environment (build 1.8.0_91-b15) Java HotSpot(TM) 64-Bit Server VM (build 25.91-b15, mixed mode)

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: "Click on the Java Platform (JDK) 8u91/8u92 download link"

Note

Warnings or important notes appear in a box like this.

Tip

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 [email protected], 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 www.packtpub.com/authors.

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 for this book 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.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Spring-MVC-Beginners-Guide-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/SpringMVCBeginnersGuideSecondEdition_ColorImages.pdf.

Errata

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 http://www.packtpub.com/submit-errata, 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 https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

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 [email protected] with a link to the suspected pirated material.

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

Questions

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

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 see 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 10 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 and software vendor's websites to install them in other operating system. In this chapter, we will learn 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 to install 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 8, which is the latest and greatest version of Java, but Java 6 or any higher version is also sufficient to complete this chapter, but I strongly recommend you use Java 8 since in later chapters of this book we may use some of the Java 8 features such as, streams and lambda expressions. Let's take a look at how we can install JDK on a Windows operating system:

Go to the Java SE download page on the Oracle website at http://www.oracle.com/technetwork/java/javase/downloads/index.html.Click on the Java Platform (JDK) 8u91/8u92 download link; this will take you to the license agreement page. Accept the license agreement by selecting the radio button option.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. If your operating system is of type 64 bit, click on the download link that corresponds to Windows x64.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 a wizard window. Just click through the next buttons in the wizard, leaving the default options alone, and click on the Close button at the end of the wizard:
JDK installation wizard

Tip

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

Now you can see the installed JDK directory in the default location; in our case, the default location is C:\Program Files\Java\jdk1.8.0_60.

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 accessible from anywhere in the file system:

Navigate to Start Menu | Settings | System | About | System info | Advanced system settings.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.Now, click on the New button in the System variables panel and enter JAVA_HOME as the variable name and enter the installed JDK directory path as the variable value; in our case, this would be C:\Program Files\Java\jdk1.8.0_91. If 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.Now, in the same System variables panel, double-click on the path variable entry; an Edit System Variable window will appear.Edit Variable value of Path by clicking the new button and enter the following text %JAVA_HOME%\bin as the value.

If you are using a Windows operating system prior to version 10, edit the path variable carefully; you should only append the text at the end of an existing path value. Don't delete or disturb the existing values; make sure you haven't missed the ; (semi-colon) delimited mark as the first letter in the text that you append:

Tip

Now click on the OK button.

Now we have installed JDK in our computer. To verify whether our installation has been carried out correctly, open a new command window, type java -version, and press Enter; you will see the installed version of Java compiler on the screen:

C:\Users\Amuthan>java -versionjava version "1.8.0_91"Java(TM) SE Runtime Environment (build 1.8.0_91-b15)Java HotSpot(TM) 64-Bit Server VM (build 25.91-b15, mixed mode)

Configuring a build tool

Building a java software project typically includes some activities as follows:

Compiling all the source codePackaging the compiled code into a JAR or WAR archive fileDeploying 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

There are other build tools that are available for building Java projects such as Gradle and Ant. We are going to use Maven as our build tool. Let's take a look at how we can install Maven:

Go to Maven's download page at http://maven.apache.org/download.cgi.Click on the apache-maven-3.3.9-bin.zip download link and start the download.

Tip

At the time of writing this book, the latest Maven version is 3.3.9; you can literally use any version of Maven after 3.0 to complete this book.

Once the download is finished, go to the downloaded directory and extract the .zip file into a convenient directory of your choice.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.Finally, append the M2_HOME variable to the PATH environment variable as well. Double-click on the path variable and click on the New button to enter %M2_HOME%\bin as the value.
Setting the M2 environment variable
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:\Users\Amuthan>mvn -versionApache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T10:41:47-06:00)Maven home: C:\Program Files\apache-maven-3.3.9Java version: 1.8.0_91, vendor: Oracle CorporationJava home: C:\Program Files\Java\jdk1.8.0_91\jreDefault locale: en_US, platform encoding: Cp1252OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"

Installing a web server

So far, we have seen 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? For this, we take the help of a web server, which 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 and servlet container. We are going to use Apache Tomcat Version 8.0, which is the latest, but you can even use version 7.0. Let's take a look at how we can install the Tomcat web server:

Go to the Apache Tomcat home page at http://tomcat.apache.org/.Click on the Tomcat 8.0 download link; it will take you to the download page.Click on the 32-bit/64-bit Windows Service Installer (pgp, md5, sha1) link; 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 a wizard window.Just click through the Next buttons in the wizard, leaving the default options alone, and click on the Finish button at the end of the wizard. Note that before clicking on the Finish button, just ensure that you have unchecked Run Apache Tomcat checkbox.

Installing Apache Tomcat with the default option works successfully only if you have installed Java in the default location. Otherwise, you have to correctly provide the JRE path according to the location of your Java installation during the installation of Tomcat, as shown in the following screenshot:

The Java runtime selection for the Tomcat installation

Configuring a development environment

We installed Java and Maven to compile and package our Java source code and installed Tomcat to deploy and run our application. So now we have to start write 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 like finding syntax errors as we type, auto-suggesting important key words, syntax highlighting, easy navigation, and so on.

An 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:

Go to the STS download page at http://spring.io/tools/sts/all.Click on the STS zip link to download the zip file that corresponds to your Windows operating system architecture type (32 bit or 62 bit); this will start the download of the zip file. The STS stable release version at the time of this writing is the STS 3.7.3.RELEASE based on Eclipse 4.6.Once the download is finished, go to the downloaded directory and extract the .zip file into a convenient directory of your choice.Open the extracted sts-bundle directory, you will find a directory called sts-3.7.3.RELEASE. Just open that directory and create a desktop shortcut for the STS.exe

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 the following two final configurations on our STS in order to use STS effectively:

Configuring Maven on STSConfiguring Tomcat on STS

The aforementioned settings are just a one-time configuration that you need to set up on your newly installed STS; you need not perform this configuration every time you open STS

Time for action - configuring Maven on STS

To build our projects, STS uses Maven build tool internally. 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:

Open STS if it is not already open.

Tip

When you open STS for the very first time after installing, 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. Provide a workspace directory path as you wish and click on the OK button.

Navigate to Window | Preferences | Maven | Installations.On the right-hand side, you can see the Add button to locate Maven's installation.Click on the Add button and choose our Maven's installed directory, and then click on the Finish button, as shown in the following screenshot:
Selecting Maven's location during the Maven configuration on STS
Now don't forget to select the newly added Maven installation as your default Maven installation by selecting the checkbox;Click on the OK button in the Preferences window and close it.

Time for action - configuring Tomcat on STS

As mentioned previously, 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 in to Tomcat. Let's configure Tomcat on STS:

Open STS from the desktop icon, if it is not already open.Go to the menu bar and navigate to Window | Preferences | Server | Runtime Environments.You can see the available servers listed on the right panel. Now click on the Add button to add our Tomcat web server.

Tip

You may also see Pivotal tc Server Developer Edition (Runtime) v3.1 listed under the available servers, which comes along with the STS installation. Although STS might come with an internal Pivotal tc Server, we chose to use the Tomcat web server as our server runtime environment because of its popularity.

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 v8.0 and select the Create a new local server checkbox. Finally, click on the Next button, as shown in the following screenshot:
Selecting the server type during the Tomcat configuration on STS
In the next window, click on the Browse button and locate Tomcat's installed directory, and then click on the OK button. You can find Tomcat's installed directory under C:\Program Files\Apache Software Foundation\Tomcat 8.0 if you have installed Tomcat in the default location. Then, click on the Finish button, as shown in the following screenshot:
Selecting the Tomcat location during the Tomcat configuration on STS

Creating our first Spring MVC project

So far, we have seen 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 much problem.

Time for action - creating a Spring MVC project in STS

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

In STS, navigate to File | New | Project; a New Project wizard window will appear.Select Maven Project from the list and click on the Next button, as shown in the following screenshot:
Maven project's template selection
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.The wizard will ask you to specify artifact-related information for your project; just enter Group Id as com.packt and Artifact Id as webstore. Then, select Packaging as war and click on the Finish button, as shown in the following screenshot:
Specifying artifact-related information during the project creation

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

We have successfully created a basic project, but we need to perform one small configuration in our pom.xml file, that is, telling Maven to use Java Version 8 while compiling and building our project. How do we tell Maven to do this? Simply add two property entries in pom.xml. Let's do the following:

Open pom.xml; you can find pom.xml under the root directory of the project itself.You will see some tabs at the bottom of the pom.xml file. Select the Overview tab.

Tip

If you do not see these tabs, then right-click on pom.xml, select the Open With... option from the context menu, and choose Maven POM editor.

Expand the Properties accordingly and click on the Create button.Now, an Add property window will appear; enter Name as maven.compiler.source and Value as 1.8, as shown in the following screenshot:
Adding the Java compiler version properties to POM
Similarly, create one more property with Name as maven.compiler.target and Value as 1.8.Finally, save pom.xml.

What just happened?

We just created the basic project structure. Any Java project follows a certain directory structure to organize its source code and 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. 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 or Jetty, and that's why we selected the Packaging style as war. Finally, you will see the project structure in Package Explorer, as shown in the following screenshot:

The project structure of the application

Tip

If you encounter a maven error on your pom file saying web.xml is missing and <failOnMissingWebXml> is set to true, then it means it is expecting a web.xml file in your Maven project because it is a web application, as we have chosen packaging as war. However, nowadays in web applications web.xml file is optional. Add the following configuration in your pom.xml within <project> tag to fix the error:

<build>     <plugins>         <plugin>             <groupId>org.apache.maven.plugins</groupId>             <artifactId>maven-war-plugin</artifactId>             <version>2.6</version>             <configuration>              <failOnMissingWebXml>false</failOnMissingWebXml>             </configuration>         </plugin>     </plugins> </build>

Spring MVC dependencies

As we are going to use Spring MVC APIs heavily in our project, we need to add the Spring jars in our project to make use of it in our development. As mentioned previously, Maven will take care of managing dependency jars 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:

Open pom.xml; you can find pom.xml under the root directory of the project itself.You will see some tabs at the bottom of the pom.xml file. Select the Dependencies tab.

Tip

If you do not see these tabs, then right-click on pom.xml, select the Open With... option from the context menu, and choose Maven POM editor.

Click on the Add button in the Dependencies section.

Tip

Don't get confused with the Add button of the Dependencies Management section. You should choose the Add button from the left-hand side of the panel.

A Select Dependency window will appear; enter Group Id as org.springframework, Artifact Id as spring-webmvc, and Version as 4.3.0.RELEASE. Select Scope as compile and then click on the OK button, as shown in the following screenshot:
Adding the spring-webmvc dependency
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.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.