In Part 1, we understood the basic journey of a request:
URL → DNS → IP → Connection → HTTP Request → Backend → Database → Response → Browser
Now let's go one step deeper.
What actually happens inside the backend when a request reaches the server? 🤔
Let's understand it using a simple Spring Boot example.
1*) Request reaches the backend 🚀*
Suppose the frontend sends:
GET /api/products/10
The request reaches our backend server.
But the backend has many different URLs/endpoints.
So the first question is:
"Which piece of code should handle this request?"
This is where routing comes in.
For example:
@GetMapping("/api/products/{id}")
public ResponseEntity getProduct(@PathVariable Long id) {
return ResponseEntity.ok(productService.getProductById(id));
}
Spring Boot sees:
GET /api/products/10
and maps it to this controller method.
2*) Controller receives the request 🎯*
The Controller is usually the entry point of our application.
Its job is to:
Receive HTTP requests
Read request data
Call the appropriate service
Return an HTTP response
For example:
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
Product product = productService.getProductById(id);
return ResponseEntity.ok(product);
}
}
Here:
GET /api/products/10
↓
ProductController
The controller doesn't ideally contain all the business logic.
So it passes the work to the Service layer.
3) Service layer handles business logic 🧠
The Service layer is where we generally put business rules and application logic.
For example:
public Product getProductById(Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Product not found"));
}
The service asks:
"I need product with ID 10. Where can I get it?"
So it calls the Repository.
Top comments (0)