Controller Layer
December 8, 2024
1 Beginner-Friendly Report: Understanding the Con-
troller Layer and Integration Testing in Spring Boot
1.1 Introduction to the Controller Layer
The Controller Layer is a crucial part of a Spring Boot application. It handles HTTP
requests from clients and maps them to appropriate services or business logic. By us-
ing controllers, we define the endpoints of our REST API, enabling clients to perform
operations like creating, reading, updating, or deleting resources.
1.1.1 Role of the Controller Layer
• Acts as the gateway to the application.
• Transforms client requests into appropriate service calls.
• Handles both incoming data (from request bodies) and outgoing responses (returned
to the client).
• Ensures that the application adheres to the principles of RESTful architecture.
1.1.2 Key Annotations in Controllers
• @RestController: Marks a class as a controller where every method returns a
response body.
• @RequestMapping: Maps HTTP requests to specific methods or classes.
• @PostMapping, @GetMapping, @PutMapping, @DeleteMapping: Map HTTP meth-
ods (POST, GET, PUT, DELETE) to specific operations.
• @RequestBody: Binds the body of a client’s request to a method parameter.
• @PathVariable: Extracts a value from the URI for use in the method.
• @Autowired: Injects dependencies like services into the controller.
[Place for Adding an Image] Add a diagram of the Controller Layer interacting with
other components, such as Services, Repositories, and Clients.
1
2 The Controllers We Built
2.1 Author Controller
Purpose: Manages authors with details like name and age.
• Endpoints:
– Create: POST /api/authors/save - Adds a new author to the system.
– Read:
∗ GET /api/authors/all: Retrieves all authors.
∗ GET /api/authors/one/{id}: Fetches a specific author by ID.
– Update: PUT /api/authors/update/{id} - Modifies an author’s details.
– Delete: DELETE /api/authors/delete/{id} - Removes an author by ID.
Example of Code: Author Controller
@RestController
@RequestMapping ( " / api / authors " )
public class AuthorController {
@Autowired
private AuthorService authorService ;
@PostMapping ( " / save " )
public ResponseEntity < AuthorDto > create ( @RequestBody
AuthorDto authorDto ) {
AuthorDto savedAuthor = authorService . createAuthor (
authorDto ) ;
return new ResponseEntity < >( savedAuthor , HttpStatus .
CREATED ) ;
}
}
2.2 Book Controller
Purpose: Handles books with attributes like title, author, category, and publish
date.
• Endpoints:
– Create: POST /api/books/save - Adds a new book.
– Read:
∗ GET /api/books/all: Retrieves all books.
∗ GET /api/books/one/{id}: Fetches a specific book by ID.
– Update: PUT /api/books/update/{id} - Updates book details.
– Delete: DELETE /api/books/delete/{id} - Deletes a book.
Example of Code: Book Controller Integration Test
2
@Test
public void testCreateBook () throws Exception {
BookDto bookDto = BookDto . builder ()
. title ( " Spring ␣ Boot ␣ Basics " )
. author ( new AuthorDto ( " John ␣ Doe " , 40) )
. category ( new CategoryDto ( " Technology " ) )
. build () ;
String bookJson = objectMapper . w ri te Va lu eA sS tr in g ( bookDto ) ;
mockMvc . perform ( M o c k M v c R e q u e s t B u i l d e r s . post ( " / api / books / save "
)
. contentType ( MediaType . APPLICATION_JSON )
. content ( bookJson ) )
. andExpect ( M o c k M v c R e s u l t M a t c h e r s . status () . isCreated ()
)
. andExpect ( M o c k M v c R e s u l t M a t c h e r s . jsonPath ( " $ . title " ) .
value ( " Spring ␣ Boot ␣ Basics " ) ) ;
}
2.3 Category Controller
Purpose: Manages categories, which classify books.
• Endpoints:
– Create: POST /api/category/save - Adds a new category.
– Read:
∗ GET /api/category/all: Lists all categories.
∗ GET /api/category/one/{id}: Fetches a specific category by ID.
– Update: PUT /api/category/update/{id} - Updates category details.
– Delete: DELETE /api/category/delete/{id} - Deletes a category.
3 Integration Testing: Ensuring the Controllers Work
Correctly
3.1 Why Testing is Important
Testing helps verify that:
• Each controller handles requests as expected.
• Data flows correctly between controllers and services.
• The system responds gracefully to errors or invalid inputs.
3
3.2 Role of MockMvc
3.2.1 What is MockMvc?
MockMvc is a Spring tool that allows us to test controllers without starting a server. It
simulates HTTP requests and provides responses just like a real client-server interaction.
3.2.2 How We Used MockMvc
• Created requests (like POST or GET) to endpoints in our controllers.
• Passed data in the requests (e.g., JSON objects for creation or updates).
• Checked responses for correctness (e.g., HTTP status codes, returned data).
Example of Code: Using MockMvc
mockMvc . perform ( M o c k M v c R e q u e s t B u i l d e r s . get ( " / api / authors / all " )
. contentType ( MediaType . APPLICATION_JSON ) )
. andExpect ( M o c k M v c R e s u l t M a t c h e r s . status () . isOk () )
. andExpect ( M o c k M v c R e s u l t M a t c h e r s . jsonPath ( " $ . length () " ) .
value (3) ) ;
4 Utility of JSON-DTO-Entity Transformation in a
Layered Project
4.1 JSON-DTO-Entity Transformation
In our layered project, the JSON-DTO-Entity transformation is a critical design
pattern that ensures clean data flow between different application layers.
• JSON:
– Represents the data exchanged between the client and the server.
– Used as the standard format for HTTP request and response bodies due to its
simplicity and readability.
• DTO (Data Transfer Object):
– Acts as an intermediary between the client and the internal layers of the ap-
plication.
– Enables validation and shaping of incoming and outgoing data without expos-
ing the database structure.
– Prevents tight coupling between external APIs and internal domain models.
• Entity:
– Represents the actual database structure used for persistence.
– The Service Layer converts DTOs into Entities for database operations and
vice versa.
[Place for Adding an Image] Add a flowchart showing the transformation from JSON
→ DTO → Entity.