38,39 €
Unleash the power of the latest Spring MVC 4.x to develop a complete application
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.
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.
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:
Seitenzahl: 372
Veröffentlichungsjahr: 2016
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
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
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.
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).
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.
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.
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.
To run the examples in the book the following softwares will be required:
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.
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:
Instructions often need some extra explanation to ensure they make sense, so they are followed by these sections.
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.
These are short multiple-choice questions intended to help you test your own understanding.
These are practical challenges that give you ideas to experiment with what you have learned.
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"
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
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:
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:
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!
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.
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 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.
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.
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.
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.
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:
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.
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:
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:
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)Building a java software project typically includes some activities as follows:
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.
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:
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.
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.
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:
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:
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.
STS is the best Eclipse-powered development environment to build Spring applications. Let's take a look at how we can install STS:
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:
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
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:
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.
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:
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.
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.
Let's create our first Spring MVC project in STS:
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:
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.
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
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>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.
Let's take a look at how we can add the Spring-related jars via the Maven configuration:
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.
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.
