45,59 €
A complete guide to build robust and scalable web applications with Spring and Angular.
This book is targeted towards Java Web Developers with a basic knowledge of Spring who want to build complete web applications in a fast and effective way. They will want to gain a stronghold on both frontend and backend development to advance in their careers.
Spring is the most popular application development framework being adopted by millions of developers around the world to create high performing, easily testable, reusable code. Its lightweight nature and extensibility helps you write robust and highly-scalable server-side web applications. Coupled with the power and efficiency of Angular, creating web applications has never been easier.
If you want build end-to-end modern web application using Spring and Angular, then this book is for you.
The book directly heads to show you how to create the backend with Spring, showing you how to configure the Spring MVC and handle Web requests. It will take you through the key aspects such as building REST API endpoints, using Hibernate, working with Junit 5 etc. Once you have secured and tested the backend, we will go ahead and start working on the front end with Angular. You will learn about fundamentals of Angular and Typescript and create an SPA using components, routing etc. Finally, you will see how to integrate both the applications with REST protocol and deploy the application using tools such as Jenkins and Docker.
This is a straightforward guide that shows how to build a complete web application in Angular and Spring.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 359
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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: August 2017
Production reference: 1210817
ISBN 978-1-78728-466-1
www.packtpub.com
Author
Ajitesh Shukla
Copy Editors
Sonia Mathur
Sameen Siddiqui
Reviewer
Parth Ghiya
Project Coordinator
Vaidehi Sawant
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Nitin Dasan
Indexer
Francy Puthiry
ContentDevelopmentEditor
Zeeyan Pinheiro
Graphics
Abhinash Sahu
Technical Editor
Pavan Ramchandani
Production Coordinator
Nilesh Mohite
Ajitesh Shukla is an accomplished software engineer with over 18 years experience in the IT industry, taking up different roles and responsibilities in startups and bigger companies, including Infosys, Computer Associates, WaveCrest, Evoke Technologies, and Raksan Consulting. He has worked on several web and mobile app projects based on technologies such as Java, Spring, Hibernate, AngularJS/Angular, ReactJS, and Ionic framework. Currently, he's interested in building cloud-native apps, cloud platforms, blockchain, and cyber security.
Ajitesh is an avid blogger and writes for websites such as DZone and Vitalflux, among many others. His hobbies include playing musical instruments, writing, and attending and organizing meetups.
Currently, Ajitesh has been working with a startup, Raksan consulting, as a Technology Evangelist where he is leading their innovation team and carving out newer solutions in the area of cloud platforms such as AWS/Google cloud, cloud-native technologies, data analytics, and blockchain.
You can follow Ajitesh on LinkedIn (/ajitesh) and GitHub (/eajitesh). You can also follow Ajitesh on Stack Overflow (/users/554132/ajitesh).
Parth Ghiya has a good experience in NodeJS, frontend technologies (Backbone JS, Angular JS, and others), portal frameworks (Liferay and EXO), and database technologies (MongoDB, MySQL, PostgreSQL, SQL, and others). He has quick adaptability to any technology and a keen desire for constant improvement.
Currently, Parth is associated with a leading open source enterprise development company, KNOWARTH Technologies, as a software consultant where he takes care of enterprise projects with regards to requirement analysis, architecture design, security design, high availability, deployment, and build processes to help customers along with leading the team.
Parth has led and delivered projects in health care, HIPAA-compliant health care portals, travel, HR, and payroll, and mobile applications.
Parth has proven skills in working with various of technologies such as Angular JS, Angular 2/4, Liferay, MySQL, Pentaho, NodeJS, Idempiere, Alfresco, MongoDB, Grunt, gulp, webpack, ionic, nativescript, Jenkins, SVN, GIT, and AWS Cloud, and is a capable full-stack developer.
Parth has been recognized with awards such as Best Employee and Special Contribution Award for his valuable contribution to the business. He is an active contributor in Stack Overflow and other forums. He is a good trainer and has mentored many people. He writes blogs and is a speaker, and he has actively organized webinars. He can be contacted at [email protected].
You can follow him on Facebook (ghiya.parth), Twitter (@parthghiya), or add him on LinkedIn (parthghiya). You can also follow Parth on Stack Overflow (https://stackoverflow.com/users/2305149/parth-ghiya).
For support files and downloads related to your book, please visit www.PacktPub.com.
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://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787284662.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Introduction to Spring Web Framework
Introduction to the Spring IOC container
What is IOC?
What is a Spring IOC container?
Introduction to Spring Web MVC
Key building blocks of a Spring Web MVC application
Introduction to the Dispatcher servlet
Building Hello World web application with Spring Boot
The Spring STS Setup in Eclipse IDE
Introduction to Spring Boot
Building Hello World web app using Spring Boot
Implementing Controllers
Handling request parameters
The RequestParam annotation
The RequestBody annotation
The PathVariable annotation
Handling Interceptors
Handling Response
Response as an instance of ModelAndView
Using @ResponseBody annotation
Creating a RESTful web service
Dockerizing a Spring Boot application
Summary
Preparing the Spring Web Development Environment
Installing the Java SDK
Installing/configuring Maven
Installing the Eclipse IDE
Import the existing Maven project in Eclipse
Creating a new Maven project in Eclipse
Installing/configuring the Apache Tomcat server
Adding/configuring Apache Tomcat in Eclipse
Installing/configuring the MySQL database
Installing/configuring the MySQL server
Using the MySQL connector
Connecting to the MySQL database from a Java class
Introduction to Docker
What are Docker containers?
What are real-world containers good for?
How do Docker containers relate to real-world containers?
Docker containers
What are the key building blocks of Dockers containers?
Installing Docker
Setting up the development environment using Docker compose
What is Docker compose?
Docker Compose Script for setting up the Dev Environment
Setting up the Tomcat 8.x as a container service
Setting up MySQL as a container service
Docker compose script to set up the development environment
Summary
Data Access Layer with Spring and Hibernate
An introduction to Hibernate
Setting up Hibernate with Spring
Setting up data source information in the application.properties file
Using annotations to wire a SessionFactory bean
Configure bean definitions
Autowire SessionFactory in DAOs
Design domain objects and database tables
User
Introduction to NamedQuery and Criteria
What is NamedQuery?
What is Criteria?
Common Hibernate operations
Data retrieval
Save/persist operation
Update/merge operation
The saveOrUpdate operation
Transaction management
Declarative transaction management
Summary
Testing and Running Spring Web App
How to run the Spring Boot app
Introduction to unit testing fundamentals
What is unit testing?
Why write unit tests?
Unit testing naming conventions
Introduction to JUnit 5
Architectural building blocks of JUnit 5
Setting up and running JUnit tests
Mocking dependencies using Mockito
Getting set up with Mockito
Introduction to mocking techniques
Unit testing controllers, services, and DAOs
Unit tests for controllers
Unit tests for Services
Unit tests for DAO components
Summary
Securing Web App with Spring Security
Introduction to Spring Security
Spring Security high level architecture
Spring Security architecture - core building blocks
Spring Security architecture - authentication
Spring Security architecture - authorization
Setting up Spring Security
Handling the login authentication
CSRF protection for API requests
CSRF prevention technique for the Angular app
CSRF prevention technique for the Spring app
Handling the logout request
OAuth2 for authentication/authorization
Introduction to OAuth2-based authentication & authorization
Spring Security and OAuth2 authentication
OAuth2 Implementation for Spring Web App
OAuth2 Implementation for Angular App
Acquiring access token
Accessing resources using access token
Summary
Getting Started with Angular
Introduction to Angular
How is Angular different from AngularJS?
AngularJS - The MVC way of building UI apps
Angular - The Component Way of Building Web Apps
Setting up the Angular development environment
TypeScript fundamentals
Forms
Template-driven forms
Reactive forms
Pipes
Directives
Structural directives
Attribute directives
Server communication
Bootstrapping an Angular app
Best practices
Summary
Creating SPA with Angular and Spring 5
Introduction to routing
Configuring Route definitions
RouterLink for navigation
What is RouterLink?
What is ActivatedRoute?
Route Guards for access control
Routing configuration design patterns
Routing within AppModule
Routing as a separate module at the app root level
Routing within feature modules
Creating a single page app (SPA)
Lean root module
Features as separate modules
Auth module
Doctor module
Route Guards for controlled access
Debugging Angular app
Debugging Angular app using Firefox and Chrome
Debugging Angular app using Augury
Summary
Unit Testing with Angular Apps
Introduction to unit testing
Unit testing tools for Angular apps
Jasmine
Karma
Protractor
Angular testing utilities
Setting up the unit test environment
Angular unit testing building blocks
Unit testing strategies
Unit testing the components
Unit testing a component with an external template
Unit testing a component with one or more dependencies
Unit testing a component with an async service
Component-under-test - DoctorListComponent
External service - DoctorService
Unit test for DoctorListComponent
Unit testing a routed component
Test doubles for Router and ActivatedRoute
Unit test for a routed component
Unit testing the services
Service under test - DoctorService
Unit test for DoctorService
Summary
Securing an Angular App
Common web application security vulnerabilities
What is Cross-Site Scripting (XSS)?
What is Cross-Site Script Inclusion (XSSI)?
What is Cross-Site Request Forgery (CSRF/XSRF)?
Securing an app from XSS
Displaying trusted HTML values
The Custom SecurityBypass pipe
Securing an app from XSSI
Securing app from CSRF/XSRF
Best practices
Summary
Integrating Angular App with Spring Web APIs
Building RESTful Spring web APIs
Configure Spring app for CORS
Key aspects of Angular data services
Promise and Observable responses
Promise for asynchronous data exchange
Observable for asynchronous data exchange
Building Angular services for RESTful integration
Invoking server APIs using the Angular HTTP service
Consuming RESTful Spring APIs using the HTTP service
Posting to RESTful Spring APIs using the HTTP service
Invoking server APIs using the Angular HttpClient service
Example of consuming RESTful Spring web APIs
Spring RESTful API for user login
Custom Angular component for managing login view
Custom Angular service for serving login functionality
Summary
Deploying the Web Application
Introduction to CI and CD
Setting up Jenkins and GitLab
Setting up Jenkins
Setting up GitLab
Setting up GitLab and Jenkins using Docker Compose
Configuring GitLab as a code repository
Creating Jenkins jobs for CI
Configuring Jenkins and GitLab for CI/CD
Configuring webhooks in GitLab
Configuring Jenkins for automated build triggers
Configuring Jenkins jobs for CD
Deploying Angular app in production
Angular app deployed on separate server
Angular app deployed on Spring app server
Summary
The book covers topics related to creating an end-to-end modern web application by using Angular for building the web app frontend and Spring framework for the backend, while integrating the apps via REST APIs and securing the API transactions using Spring Security concepts. Traditionally, Java developers have been used to developing the backend of a web application, while the frontend (UI) has been left for UI developers. However, this book aims to enable and empower Spring web application developers to quickly get started with Angular and build frontend (UI) components as well along with the backend components.
The following are some of the key challenges that we will address in this book:
Building Angular apps (especially for Spring web developers)
Security
Integration
Deployment
Here are some of the key milestones that we will cover in this book:
Preparing development environments, where we highlight the usage of Docker containers to create a development environment that is easy to spin up and decommission once done
Creating Spring Boot web application backend components such as API endpoints, controllers, services, and data access components using the Spring Web MVC framework and Hibernate
Creating web application frontend (UI) or rather single-page apps (SPAs) using Angular concepts such as Components, Services, Routing, and so on
Unit testing both Spring and Angular apps
Building and running both Spring and Angular apps
Securing the API transactions using Spring security and also taking care of security aspects related to the content displayed on the frontend (Angular apps)
Integrating Angular apps with Spring Web app REST endpoints
Deploying web apps based on Continuous Delivery principles
Chapter 1, Introduction to Spring Web Framework, provides an introduction to the Spring and the Spring Web MVC framework along with code samples for configuring Spring MVC and creating Spring Boot web applications.
Chapter 2, Preparing the Spring Web Development Environment, provides information on the necessary tools (along with code samples) that may be required to be installed/configured for working with Spring web apps.
Chapter 3, Data Access Layer with Spring and Hibernate, covers the concepts and code samples related to setting up Hibernate with Spring.
Chapter 4, Testing and Running Spring Web App, describes concepts and code samples related to running a Spring web app and writing unit tests for different types of web app components such as controllers, services, DAOs, and so on.
Chapter 5, Securing Web App with Spring Security, explains the concepts related to Spring security such as authentication, CSRF protection, and so on API requests made by Angular single page apps (SPAs).
Chapter 6, Getting Started with Angular, covers Angular fundamentals along with code samples and instructions on how to set up the Angular app development environment.
Chapter 7, Creating SPA with Angular and Spring 5, explains the key concepts related with creating single page applications using Angular and Spring.
Chapter 8, Unit Testing with Angular Apps, takes you through the steps required to set up environment and write/execute unit tests with Angular components/services, and so on.
Chapter 9, Securing Angular Apps, describes concepts related to protecting the content displayed by Angular apps from common web vulnerabilities and attacks such as cross-site scripting (XSS), cross-site request forgery (CSRF), and cross-site script inclusion (XSSI).
Chapter 10, Integrating Angular Apps with Spring Web APIs, describes concepts related to how Angular apps can be integrated with Spring endpoints based on the REST protocol.
Chapter 11, Deploying Web Applications, describes concepts related to deploying web applications using continuous delivery principles.
Developers will be required to work with some of the following software:
Java
A Java framework such as Spring or Hibernate
The Eclipse IDE (optional)
Angular
The Javascript IDE (optional) for working with Angular code
Jenkins
GitLab
Docker
This book is targeted at Java web developers, with a basic knowledge of Spring, who want to build complete web applications in a fast and effective way. It will help those who want to gain a stronghold on both frontend and backend development to advance in their careers.
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: "In order to bypass Angular built-in sanitization for the value passed in, Angular provides a class such as DomSanitizer."
A block of code is set as follows:
@RequestMapping("/") String home() { return "Hello world. How are you?"; } public static void main(String[] args) { SpringApplication.run(HelloWorldApplication.class, args); }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
@Controller
@RequestMapping("/account/*")
public class UserAccountController {
@RequestMapping
public String login() { return "login"; } }
Any command-line input or output is written as follows:
docker pull gitlab/gitlab-ce
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: "It is required to add GitLab username/password credentials which can be achieved by clicking on Add button"
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:
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
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Web-Apps-with-Spring-5-and-Angular. 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/BuildingWebAppswithSpring5andAngular_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, you will learn about the key concepts of the Spring framework, and how we can use this framework to develop web applications. The following are some of the topics that will be dealt with:
Introduction to the Spring IOC container
Introduction to the Spring web MVC
Building a
Hello World
web application with Spring Boot
Implementing controllers
Handling request parameters
Handler interceptors
Handling responses
Creating a RESTful Web Service
Dockerizing Spring Boot Application
Starting with the section, Implementing controllers in this chapter, we will start building a sample healthcare web application to demonstrate the key concepts. The following are some of the key functionalities of the sample app which will be covered as part of building the app:
Signup for doctors and patients
Logging into the app
Searching for doctors based on their specialties
Fixing an appointment
Interacting with the doctor
As a primer to learning the Spring Web MVC framework, it is recommended to learn some of the following object-oriented design principles, which act as a basis for the Spring Web framework. Note that these principles form a part of the famous Single responsibility, Open-closed, Liskov substitution, Interface segregation, and Dependency inversion (SOLID) principle by Robert Martin (Uncle Bob):
Single Responsibility Principle (SIP)
: This principle states that a module, a class, or a method should have the responsibility of serving just one functionality of the underlying software. In other words, a module, a class or a method should have just one reason to change. Modules or classes following SIP have high cohesiveness, and thus, can be termed as reusable entities. Classes violating SIP are found to have high cyclomatic complexity, and thus, low testability.
Open-Closed Principle (OCP)
: This principle states that the classes are open for extension, but closed for modification. Based on this principle, the core classes of the Spring Web MVC consist of some methods which are marked as final, which, essentially, means that these final methods can not be overridden with custom behavior.
Liskov Substitution Principle (LSP)
: This principle states that if a class
A
(child class) is derived from class
B
(parent class), then the object of class
B
can be replaced by (or substituted with) an object of class
A
without changing any of the properties of class
B
. It can be inferred that the functions which use references of the base class must be able to use objects of the derived class without the need to know about the implementation of the base class. For example, let's consider the square and rectangle example. In the case where square derives from rectangle, then, as per LSP, an object of the class
Rectangle
can be substituted with an object of the class
Square
. However, in reality, this is not possible without doing appropriate implementation in the
Square
class setter methods, where setting either of length or breadth sets another side of equal length, and/or code using these classes do appropriate checks to find out whether the object is an instance of the class
Square
or
Rectangle
.
Interface Segregation Principle (ISP)
: This principle states that the fat interfaces having large number of API definitions should be split into smaller interfaces defining a set of cohesive APIs. Not following this principle leads to the client providing empty implementations for unwanted APIs.
Dependency Inversion Principle (DIP)
: This principle is pretty much related to the IOC principle, which is discussed in the next section. It states that the dependency relationship between higher-level modules with low-level modules is reversed, thus making these modules independent of each other's implementation details.
Before we get into understanding what is Spring IOC Container, let us quickly learn what is IOC.
In this section, we will learn the key elements of the Spring Web model-view-controller (Spring Web MVC) framework, and how to quickly get started with a Spring web application using the Spring Web MVC components. The following will be covered in detail in this section:
Key building blocks of a Spring Web MVC application
Introduction to the Dispatcher servlet
In this section, we will learn about the key building blocks of a Spring web MVC application. The following diagram represents the key building blocks:
The following are the details in relation to the preceding diagram:
Dispatcher servlet
: Dispatcher servlet, also termed the
front controller
, is at the core of the Spring Web MVC framework. Simply speaking, the Dispatcher servlet determines which
controller
class and method needs to be called when a page request or an API request arrives. In addition, it sends the response using the appropriate JSP page or JSON/XML objects. It dispatches the incoming requests to the appropriate handlers (custom controllers) with different handler mappings. This is integrated with the Spring IOC container, which allows it to use all the features that the Spring framework provides.
Handler Mappings
: Handler mappings are used to map the request URL with the appropriate handlers such as controllers. The Dispatcher servlet uses the handler mappings to determine the controllers which will process the incoming requests. The handler mappings are specified in the XML file, or as annotations such as
@RequestMapping
,
@GetMapping
, or
@PostMapping
, and so on. The following diagram represents the
@RequestMapping
annotation that is used for URL mapping.
Handler Interceptors
: Handler interceptors are used to invoke preprocessing and post-processing logic before and after the invocation of the actual handler method respectively.
Controllers
: These are custom controllers created by the developers and used for processing the incoming requests. The controllers are tagged with annotations such as
@Controller
or
@RestController
. Controllers are used to access the application behavior through one or more service interfaces. Controllers are used to interpret the user input, pass them to the services for implementation of business logic, and transform the service output into a model which is presented to the user as a view. The following diagram shows the
@Controller
annotation which represents the
DemoApplication
class to play the role of a controller:
Services
: These are the components coded by the developers. These components contain the business logic. One or more methods of services are invoked from within the
Controller
methods. Spring provides annotations such as
@Service
for identifying services. The following code represents the service class
UserService
, which consists of a method,
getUsername
. Pay attention to the
@Service
annotation. Note how the instance of
UserService
is defined in
@Controller
, as shown in the preceding code, and the method
getUsername
is invoked on the instance of
UserService
.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.services.dao.UserDAO; import com.services.domain.User;
@Service
("userService") public class UserService { @Autowired private UserDAO userDAO; public String getUsername(User user) { return userDAO.getUsername(user); } }
Data Access Objects (DAO)
: The classes which represent DOA, are used to do data processing with the underlying data sources. These classes are annotated with annotations such as
@Repository
. The preceding code of
UserService
consists, a DAO, namely,
UserDAO
. Note the
@Repository
annotation used by the class,
UserDAO
, in the following code:
import org.springframework.stereotype.Repository; import com.services.domain.User;
@Repository
("userDAO") public class UserDAO { public String getUsername(User user) { return "Albert Einstein"; } }
View Resolvers
: View resolvers are components which map view names to views. They help in rendering models in the browser based on different view technologies such as JSP, FreeMarker, JasperResports, Tiles, Velocity, XML, and so on. Spring comes with different view resolvers such as
InternalResourceViewResolver
,
ResourceBundleViewResolver
,
XMLViewResolver
, and others. View resolvers are used by the Dispatcher servlet to invoke the appropriate view components.
Views
: Views are used to render the response data on the UI. They can be represented using different technologies such as JSP, Velocity, Tiles, and so on.
In this section, we will learn about the core component of a Spring web MVC application, the Dispatcher servlet.
As introduced in the previous section, Dispatcher servlet is the front controller which processes the user requests by invoking the appropriate components such as handler mappings, interceptors, adapters, custom controllers, services, DOA, view resolver, and finally, the views. The following diagram represents the web request/response workflow of the Dispatcher servlet:
As per the preceding diagram, the journey of a request/response through a Spring web MVC application looks like the following:
The user requests arrive at the server, and are intercepted by the Dispatcher servlet.
The Dispatcher servlet gets a handler object (primarily, an instance of
HandlerExecutionChain
) from the
HandlerMapping
object based on the URL mapping. URL mappings can be defined with the
web.xml
file or as annotations on the Controllers' methods.
One or more instances of the
HandlerInterceptor
objects are retrieved from the handler object, and preprocessing logic is processed on the request object.
The instance of
HandlerAdapter
is retrieved from the handler object, and the
handle
method is invoked. This results in execution of logic within the
controller
class. In the preceding diagram (
Figure 3
), the request with
RequestMapping
as "
/
" leads to the execution of code within the
home
method as part of this step.
The post-processing logic on the
HandlerInterceptor
instances is executed. This is the final step before the
rendering
method is invoked.
The
ViewResolver
instance is used to retrieve the appropriate view component.
The
render
method is invoked on the instance of view.
In this section, we will learn how to quickly build a web application using Spring Boot. The following will be covered in this section:
The
Spring Tool Suite
(
STS
) setup in Eclipse IDE
Introduction to Spring Boot
Building the Hello World web app using Spring Boot
Spring Tool Suite (STS) provides the development environment for Spring-powered enterprise applications. This can be easily downloaded from the Eclipse marketplace in the following manner:
Within the Eclipse IDE, click on
Help
|
Eclipse Marketplace...
and search for Spring STS by submitting Spring STS in the
Find
text field. The search result would show up different versions of STS for different Eclipse versions.
Choose the appropriate version and install. The most current version is
3.9.0.RELEASE
.
Restart Eclipse, and you are all set to create your first Spring Boot web application.
Spring Boot is a quick and easy way to get up and running with production-grade standalone applications in no time. If you hated all the XML configurations required to be set for creating a Spring web application, Spring Boot helps us to get away with all those troubles, and lets us focus on developing the application from the word go. The following are some of the key attributes of a Spring Boot application:
Requires no XML configuration or code generation.
Automatically configures Spring wherever appropriate and possible.
Supports embedded web servers such as Tomcat, Jett, and so on. One of the key disadvantages while working with the Spring web framework prior to Spring Boot was deploying these apps explicitly on the web server either manually, or using some tools/scripts. This is no more required with Spring Boot, as it comes with support for embedded web servers.
Helps to quickly and easily get started with microservices development. Spring Boot has seen great adoption in recent times thanks to the advent of micro-services architecture style apps. Spring Boot supports creation of micro-services in the form of a JAR file, which could easily be deployed within a server container.
Supports features such as health checks, metrics, and so on.
Provides useful annotations such as
@ConfigurationProperties
to accomplish tasks such as loading properties' details from the
application.properties
file.
In this section, we will go through the steps required to build a Hello World Web App using Spring Boot. The following given steps assume that you have set up Spring STS within your Eclipse IDE by following the steps given earlier. Now, with the steps given next, one can set up the Hello World web app in an easy manner:
Press
Ctrl
+
N
to open up the
Project creation Wizard
dialog box.
Write
Spring
in the
Wizards
text field. This will show various project options related to Spring projects. Select the option
Spring Starter Project
, and click on
Next
.
Name the project
HelloWorld
, or leave the default name
demo
, and click on
Next
:
Select
Web
in the list of dependencies as shown in the following screenshot, and click on
Finish
:
Clicking on
Finish
will create a
HelloWorld
