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
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>
The class containing the
main
method shouldn't implementCommandLineRunner
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 therun
method.In the
main
src package (insidecom.version1.SpringJDBCIntro
package ) create a new package calledservices
. Create a new class in this package, DepartmentService and annotate it with@Service
annotation from theorg.springframework.stereotype
package.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 thefindAllDepartments()
method from the injected repository class.public List<Department> getAllDepartments(){ return deptRepository.findAllDepartments(); }
Similarly to step 4, create a new package called
controllers
. Within this package create a new Java class calledDepartmentController
. Annotate it with@RestController
annotation importing theorg.springframework.web.bind.annotation
package.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!Annotate this method with
@GetMapping
and create a new endpoint url, i.e. "/departments".@GetMapping("/departments") public List<Department> getAllDepartments(){ return deptService.getAllDepartments(); }
Run the application. the output in the terminal should look like this
Notice that the in-built application server is running on port 8080.
Open up your browser and type in
localhost:8080/departments
. After you press enter you should see a list of departments in JSON format.