Home Web Development Building Web Apps with Spring 5 and Angular 4

Building Web Apps with Spring 5 and Angular 4

By Ajitesh Kumar Shukla
books-svg-icon Book
Subscription FREE
eBook + Subscription $15.99
eBook $43.99
Print + eBook $54.99
READ FOR FREE Free Trial for 7 days. $15.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
READ FOR FREE Free Trial for 7 days. $15.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
Subscription FREE
eBook + Subscription $15.99
eBook $43.99
Print + eBook $54.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
  1. Free Chapter
    Introduction to Spring Web Framework
About this book
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.
Publication date:
August 2017
Publisher
Packt
Pages
370
ISBN
9781787284661

 

Chapter 1. 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 with the doctor
 

Introduction to the Spring IOC container


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. 

What is IOC?

Many a times, the Hollywood principle of Don't call us, we will call you is used to explain the concept of Inversion of Control. In Hollywood, this is what one gets to hear after auditioning is done. If we apply this principle to the programming model, instead of the classes creating dependencies along with serving functionality, the dependencies are appropriately made available to the classes during runtime, and the classes just need to focus on delivering the functionality.

Simply speaking, Inversion of Control (IOC) is about inverting the flow of control that the traditional programming model used to have in terms of objects at the higher-level handling the creation and management of lower-level objects' (can also be termed as dependencies) life cycle. In the IOC programming model, higher-level objects rather receive one or more instances of these dependencies from the calling object or external framework. This is why IOC is also termed Dependency Injection, wherein the dependencies are injected appropriately, and, objects bother themselves solely with the program execution and not with the object creation. Inversion of Control is related to the object-oriented principle known as the Dependency Inversion Principle (DIP), coined by Robert Martin (Uncle Bob).

Let's take a look at the following code sample, which represents higher-level objects handling the creation of lower-level objects (dependencies):

    /*
     * This class demonstrates the dependency of higher-level object   
     * (DrawWithoutIOC)
     * onto lower level objects such as Rectangle, Square which are 
     * created within 
     * Shape class based on the value of shapeType which is passed as a 
     * method 
     * parameter to draw method.
     */

    public class DrawWithoutIOC {

      Logger logger = Logger.getLogger(DrawWithoutIOC.class.getName());

      public void draw(String shapeType) {
        Shape shape = new Shape();
        try {
          shape.draw(shapeType);
        } 
        catch (UndefinedShapeException e) {
          logger.log(Level.INFO, e.getMessage(), e);
        }
      }
    /*
     * Note that Shape class creates instances of Rectangle or Square   
       class
     * based on the value of shapeType. Any new value that needs to be   
       supported requires change in the draw method of Shape class.
     */

      private class Shape {
        public void draw(String shapeType) throws 
          UndefinedShapeException 
        {
          if(shapeType.equals("rectangle")) {
            Rectangle rectangle = new Rectangle();
            rectangle.draw();
          } else if(shapeType.equals("square")) {
            Square square = new Square();
            square.draw();
          } else {
            String shapeNotSupportedMessage = "Shape " + shapeType + " 
                   not supported";
            logger.log(Level.INFO, shapeNotSupportedMessage);
            throw new UndefinedShapeException 
              (shapeNotSupportedMessage);
          }
        }
      }

      public static void main(String[] args) {
        DrawWithoutIOC drawWithoutIOC = new DrawWithoutIOC();
        drawWithoutIOC.draw("circle");
      }
    }

Let us take a look at the class DrawWithIOC, which accepts the implementation of the Shape object in its public constructor. Note that the dependencies, such as different implementations of the Shape object, are rather injected, and code just does the execution of business logic without bothering about creation of objects related to the different implementations of Shape. Other alternatives to injecting the dependencies are passing arguments to a factory method of the class, or through properties that are set on the object instance:

    /**
     * In this class, the Shape is passed as parameter to DrawWithIOC   
     * constructor. 
     * draw method on a DrawWithIOC object just invokes the draw method  
     * on Shape object. 
     * It, no longer, manage the creation of Shape object based on 
     * shapeType and there upon, invoke the draw method.
     **/

    public class DrawWithIOC {
      Logger logger = Logger.getLogger(DrawWithIOC.class.getName());

      private Shape shape;

      public DrawWithIOC(Shape shape) {
        this.shape = shape;
      }

      public void draw() { 
        this.shape.draw(); 
      } 

      public static void main(String[] args) {
        Shape shape = new Rectangle();
        DrawWithIOC drawWithIOC = new DrawWithIOC(shape);
        drawWithIOC.draw();
      }
    }

What is a Spring IOC container?

A Spring IOC container is a framework which, basically, manages the life cycle of plain old Java objects (POJOs), and injects them into the application as required. Java objects define their dependencies using one of the following methods:

  • Dependencies are passed as arguments to the constructor method of the object. See how the object is passed as an argument to the constructor method in the example cited in the previous section.
  • Dependencies are passed as arguments to the setter method of the object.
  • Dependencies are passed as arguments to a factory method of the object.

A Spring IOC container injects the dependencies after it creates the beans. Note the fact that dependencies are no longer managed by Java objects. They are rather managed and injected by the framework, and hence, Inversion of Control.

The following are the packages which are core to the IOC container:

  • org.springframework.beans
  • org.springframework.context

It is the interface, org.springframework.context.ApplicationContext (sub-interface of the interface, BeanFactory), which represents the Spring IOC container and is responsible for managing the life cycle of beans. The instructions related to creating, configuring, and assembling the objects is termed Configuration Metadata. The configuration metadata is often represented using Java annotations or XML. A Java application using Spring IOC Container is created by combining Business POJOs with the previously mentioned configuration metadata, and passing it on to the IOC Container (an instance of ApplicationContext). The same is represented using the following diagram:

Figure 1: Java Application with Spring IOC Container

Let's illustrate the preceding diagram with an example. The following code represents how a service, namely, UserService is instantiated using Spring IOC container in a Spring Boot web application. Notice how the annotation-based autowiring feature has been used to have ApplicationContext autowired to the userService field in this code:

    package com.example;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    import com.services.UserService;
    import com.services.domain.User;

    @Controller
    @SpringBootApplication (scanBasePackages={"com.services"})
    public class DemoApplication {

@Autowired
        private UserService userService;

        @RequestMapping("/")
        @ResponseBody
        String home() { 
            User user = null;
            return "Hello " + userService.getUsername(user) + ". How are you?";
        }

        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
 

Introduction to Spring Web MVC


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

Key building blocks of a Spring Web MVC application

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:

Figure 2: Key building blocks of Spring web MVC framework

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:

Figure 3: Representing handler mappings (URL mapping) and Controller annotation

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

Introduction to the Dispatcher servlet

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:

Figure 4: Web request/response flow across the Dispatcher servlet

As per the preceding diagram, the journey of a request/response through a Spring web MVC application looks like the following:

  1. The user requests arrive at the server, and are intercepted by the Dispatcher servlet.
  2. 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.
  1. One or more instances of the HandlerInterceptor objects are retrieved from the handler object, and preprocessing logic is processed on the request object.
  2. 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.  
  3. The post-processing logic on the HandlerInterceptor instances is executed. This is the final step before the rendering method is invoked. 
  4. TheViewResolver instance is used to retrieve the appropriate view component.
  5. The render method is invoked on the instance of view.
               
About the Author
  • Ajitesh Kumar Shukla

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

    Browse publications by this author
Latest Reviews (8 reviews total)
sono trattate tutte le funzionalità ma, secondo me, adatto per che conosce l'argomento e vuole testare le conoscenze già in acquisite.
Poorly written. Needs an experienced editor....
Topics aren't covered in depth
Building Web Apps with Spring 5 and Angular 4
Unlock this book and the full library FREE for 7 days
Start now