The @RestController Annotation
In Spring Boot, controllers are the front desk of your application. They receive incoming HTTP requests and decide how to respond. The @RestController annotation marks a class as a web controller that handles RESTful requests.
Under the hood, @RestController is a combination of @Controller and @ResponseBody. This means every method in the class automatically serializes its return value to JSON โ no need to annotate each method individually.
Handling HTTP Requests
Each public method in a controller can be mapped to a specific HTTP endpoint. You combine @RestController with mapping annotations like @GetMapping or @PostMapping to define which URL and HTTP method each method handles.
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
public List<Product> getAllProducts() {
return productService.findAll();
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.save(product);
}
}
Request and Response Objects
Spring provides HttpServletRequest and HttpServletResponse objects if you need low-level access. But in most cases, you'll work with simplified parameters and return types that Spring handles automatically.
The framework reads the request body, converts it to your Java object, and converts your return value back to JSON. This lets you focus on business logic instead of serialization details.
Controller Best Practices
Keep your controllers thin. They should only handle HTTP concerns like request parsing and response formatting. Delegate the actual business logic to service classes.
Name your controllers after the resource they manage โ UserController, OrderController, and so on. Use consistent URL naming, and always return appropriate HTTP status codes to indicate success or failure.