Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $9.99/month after trial. Cancel anytime.

Building Web Apps with Spring 5 and Angular
Building Web Apps with Spring 5 and Angular
Building Web Apps with Spring 5 and Angular
Ebook609 pages3 hours

Building Web Apps with Spring 5 and Angular

Rating: 0 out of 5 stars

()

Read preview

About this ebook

A complete guide to build robust and scalable web applications with Spring and Angular.

About This Book
  • This hands on guide will teach you how to build an end-to-end modern web application using Spring and Angular.
  • It is easy to read and will benefit Java developers who have been used to develop the back-end part of web application while front-end (UI) has been left for UI developers.
  • Learn the core aspects involved in developing the backend and the UI, right from designing to integrating and deploying.
Who This Book Is For

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.

What You Will Learn
  • Set up development environment for Spring Web App and Angular app.
  • Process web request and response and build REST API endpoints.
  • Create data access components using Spring Web MVC framework and Hibernate
  • Use Junit 5 to test your application
  • Learn the fundamental concepts around building Angular
  • Configure and use Routes and Components.
  • Protect Angular app content from common web vulnerabilities and attacks.
  • Integrate Angular apps with Spring Boot Web API endpoints
  • Deploy the web application based on CI and CD using Jenkins and Docker containers
In Detail

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.

Style and approach

This is a straightforward guide that shows how to build a complete web application in Angular and Spring.

LanguageEnglish
Release dateAug 24, 2017
ISBN9781787281523
Building Web Apps with Spring 5 and Angular

Related to Building Web Apps with Spring 5 and Angular

Related ebooks

Programming For You

View More

Related articles

Reviews for Building Web Apps with Spring 5 and Angular

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Building Web Apps with Spring 5 and Angular - Ajitesh Shukla

    Building Web Apss with Spring 5 and Angular

    Building Web Apps with Spring 5 and Angular

    Build modern end-to-end web applications using Spring and Angular

    Ajitesh Shukla

    BIRMINGHAM - MUMBAI

    Building Web Apps with Spring 5 and Angular

    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

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham

    B3 2PB, UK.

    ISBN 978-1-78728-466-1

    www.packtpub.com

    Credits

    About the Author

    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).

    I would like to dedicate this book to my wife, two lovely daughters, my parents and family members whose love, support and blessings have always been there with me, inspiring and supporting me in all endeavors I undertook, while also playing the role of critique and making sure I get the job done in best possible manner. I would like to convey my sincere thanks to my friends and colleagues who have always helped me achieve greater things in life while constantly inspiring me in take up newer challenges and give my best to each one of them. Special thanks to my current employer, Raksan consulting, who motivated me enough to cross over this milestone. Last but not the least, I would like to thank Packt Publishing for giving me the opportunity to author this book.

    About the Reviewer

    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).

    Thank you is the best prayer that anyone could say and I say that a lot. I would like to tender my humble thanks to my family, teachers, and my extended family (all my friends and colleagues) who have helped me constantly excel myself and be a humble person, and gave me their time--the most thoughtful gift of all. I would like to thank KNOWARTH for providing new opportunities to constantly enhance myself. I would also like to thank Packt Publishing for giving me the opportunity to review this book.

    www.PacktPub.com

    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.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    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!

    Table of Contents

    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

    Preface

    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

    What this book covers

    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.

    What you need for this book

    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

    Who this book is for

    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.

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

    Warnings or important notes appear like this.

    Tips and tricks appear like this.

    Reader feedback

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

    To send us general feedback, simply e-mail [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.

    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!

    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/BuildingWebAppswithSpring5andAngular_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.

    Introduction to Spring Web Framework

    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

    Enjoying the preview?
    Page 1 of 1