/
17 - Spring Web - Exercise

17 - Spring Web - Exercise

Overview

This exercise will work with the project created in the previous section. We will use the existing connection to the database and add a ReST API to expose the queried data.

Task

  1. Open the project create in the previous exercise and add the following dependency into the pom.xml file. If you need to create a new project using Spring Initializr, include Spring Web dependency.

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  2. The class containing the main method shouldn't implement CommandLineRunner interface as now we would like our application to act as a server and actually be deployed on the in-build Tomcat server. Comment our the run method.

  3. In the main src package (inside com.version1.SpringJDBCIntro package ) create a new package called services. Create a new class in this package, DepartmentService and annotate it with @Service annotation from the org.springframework.stereotype package.

  4. Autowire your DepartmentRepository bean into the service class. Create a method that will return a list of departments, does not take any parameters and calls the findAllDepartments() method from the injected repository class.

    public List<Department> getAllDepartments(){ return deptRepository.findAllDepartments(); }
  5. Similarly to step 4, create a new package called controllers. Within this package create a new Java class called DepartmentController. Annotate it with @RestController annotation importing the org.springframework.web.bind.annotation package.

  6. Create a new method that returns a list of departments, does not take any parameters and call the method getAllDepartments() from your service class. Make sure you autowire your service class into the controller!

  7. Annotate this method with @GetMapping and create a new endpoint url, i.e. "/departments".

    @GetMapping("/departments") public List<Department> getAllDepartments(){ return deptService.getAllDepartments(); }
  8. Run the application. the output in the terminal should look like this

  9. Notice that the in-built application server is running on port 8080.

  10. Open up your browser and type in localhost:8080/departments . After you press enter you should see a list of departments in JSON format.

Related content