Book Image

Building Web Apps with Spring 5 and Angular

By : Ajitesh Kumar Shukla
Book Image

Building Web Apps with Spring 5 and Angular

By: Ajitesh Kumar Shukla

Overview of 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.
Table of Contents (18 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Creating a RESTful web service


In this section, you will learn how to create a RESTful web service. The concepts explained earlier in this chapter will be used.

The following are some of the key aspects of creating a RESTful web service. Let's take the example of retrieving the doctors' list based on the specialties, location, and so on.

  • Create a controller representing the RESTful endpoint: In the following code, note the usage of the @RestController annotation, which is used to represent the annotation @Controller and @ResponseBody. The controller has a method, searchDoctor, for handling the request represented using the URL such as /doctors?location=xxx&speciality=yyy. Note the @RequestMapping annotation and its attributes, especially, "produces", which signifies the fact that the output sent to the user will be in the JSON format.
    @RestController
    public class DoctorSearchController {

      @Autowired
      DoctorService docService;

      @RequestMapping(value="/doctors", method=RequestMethod.GET, 
                      produces="application/json")
      public DoctorList searchDoctor(
             @RequestParam(value="location", required=false) String location,
@RequestParam(value="speciality", required=false) String speciality) 
      {
          DoctorList docList = docService.find(location, speciality);
        return docList;
      }
    }

The following is how the DoctorService implementation may look like:

    @Service
    public class DoctorServiceImpl implements DoctorService {

        @Autowired 
        private DoctorDAO doctorDAO;

        @Override
        public List<Doctor> findByLocationAndSpeciality(String location, String 
      speciality) {
          return doctorDAO.findByLocationAndSpeciality(location, specialityCode);
        }
    }

The following is how the DoctorDAO implementation may look like:

    @Repository
    @Transactional
    public class DoctorDAOImpl implements DoctorDAO {

      private SessionFactory sessionFactory;

      @Autowired
      public DoctorDAOImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
      }

      @Override
      public List<Doctor> findByLocationAndSpeciality(String location, String speciality) {
        Session session = this.sessionFactory.getCurrentSession();
        TypedQuery<Doctor> query = session.getNamedQuery("findByLocationAndSpeciality");
        query.setParameter("location", location);
        query.setParameter("speciality", speciality);
        List<Doctor> doctors = query.getResultList();
        return doctors;
      }
    }
  • Create a RESTful API: For retrieving the list of doctors based on location and speciality, the URL could look like  http://localhost:8080/doctors?location=xxx&speciality=yyy.
  • Identify the method of processing incoming requests data: @RequestParam will be used to process the incoming requests data as mentioned in the preceding URL. In the previous code, note how @RequestParam is used for processing the value of both the location and the specialty parameter. The following code represents the same:
        public DoctorList searchDoctor(
        @RequestParam(value="location", required=false) 
        String location, 
        @RequestParam(value="specialty", required=false) 
        String speciality) {
            // Code goes here
        }
  • Create a class representing ResponseBody: The return value is the DoctorList object, which consists of a list of Doctors. The following code represents the DoctorList object which is a list of the Doctor object:
    // The class representing the list of Doctor; Returned as a response
    public class DoctorList {
      private List<Doctor> doctors;

      public DoctorInfo(List<Doctor> doctors) {
        this.setDoctors(doctors); 
      }
      public List<Doctor> getDoctors() {
        return doctors;
      }
      public void setDoctors(List<Doctor> doctors) {
        this.doctors = doctors;
      }
    }

The following represents the Doctor class which is returned as part of the response object:

    public class Doctor {

      private String id;
      private String firstName;
      private String lastName;
      private String specialityCode;

      public String getId() {
        return id;
      }
      public void setId(String id) {
        this.id = id;
      }
      public String getFirstName() {
        return firstName;
      }
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
      public String getLastName() {
        return lastName;
      }
      public void setLastName(String lastName) {
        this.lastName = lastName;
      }
      public String getSpecialityCode() {
        return specialityCode;
      }
      public void setSpecialityCode(String specialityCode) {
        this.specialityCode = specialityCode;
      }
    }
  • Client response: The client receives the response body in the JSON format. The following is a sample response which is returned by the execution of the preceding code:
    [{
     "id": "doc1",
     "firstName": "Calvin",
     "lastName": "Hobbes",
     "specialityCode": "pediatrics"
    },
    {
      "id": "doc2",
      "firstName": "Susan",
      "lastName": "Storm",
      "specialityCode": "cardiology"
    }]