A controller is a class that handles web requests. In a browser-facing Spring MVC application, it can prepare model data and pass control to a view that renders HTML. The controller handles the request; the view handles the presentation. section 1.3.1 section 2.1
Listing 1.4 The home page controller
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller #1
public class HomeController {
@GetMapping("/") #2
public String home() {
return "home"; #3
}
}
Start with a home page: @Controller lets Spring discover the class and create it as a bean. @GetMapping("/") sends GET requests for the root path to home(). The returned string, "home", is a logical view name; with Thymeleaf on the classpath, a Thymeleaf template can provide that view. This handler needs no model data. section 1.3.1
A page with changing data needs more work. For a taco-design page, the controller supplies ingredient choices to the model, and the view renders them for the browser. Ingredient data is supplied by the controller initially; fetching it through a database repository is a later step. section 2.1
A larger controller can group related requests. @RequestMapping("/design") at class level selects paths beginning with /design; a method-level @GetMapping then handles GET /design. @SessionAttributes("tacoOrder") keeps the order placed in the model across requests. Other request-mapping annotations include @PostMapping for POST requests. section 2.1.2
@GetMapping(params="recent")
public Flux<Taco> recentTacos() {
return tacoRepo.findAll().take(12);
}
An API controller can return data instead of a view. Here a reactive GET handler returns a Flux of at most 12 tacos directly from a reactive repository. Spring WebFlux retains the annotation-based request-handling pattern used by Spring MVC; the framework subscribes to the returned Flux. section 12.1.2







