Controllers

Basic Spring
≈ 2 min read

A controller as an adapter between HTTP and the application

In Spring MVC, a controller is a Spring bean whose methods can handle web requests. It receives data in a form convenient for Java code, calls the required services, and returns a result that Spring MVC then turns into an HTTP response.

@Controller
class ProductController {

    private final ProductService productService;

    ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping("/products")
    String products(Model model) {
        model.addAttribute("products", productService.findAll());
        return "products";
    }
}

The @Controller annotation makes the class a candidate for an MVC controller. In the example, the method gets data from a service, puts it into Model, and returns a view name. The controller itself does not create the service and should not absorb its business logic.

Why controllers should stay thin

If a controller starts calculating prices, managing transactions, or containing complex domain rules, the web layer quickly becomes harder to reuse and test. A controller usually only needs to read incoming data, call the appropriate application operation, and form a web result.

@Controller does not automatically mean “return JSON”. Working with the HTTP response body and the special controller variant for REST will be covered later.