Recipes
Recipe: Configuring a Spring MVC Controller
A controller recipe turns a model type into a working Spring MVC handler. This recipe covers the request mapping, the form backing object and the view names.
Controllers sit between the browser and the service layer. A controller recipe reads a model type, then writes a handler class with request mappings, a form backing object and view names. The recipe is intentionally small so that it is easy to read and easy to adjust.
Inputs the recipe expects
- A type with the controller stereotype.
- At least one service reference, so the handler has something to call.
- A view prefix and suffix, usually set once at project level.
- An optional list of actions such as list, show, create, edit and remove.
What the recipe writes
The recipe creates a class annotated with @Controller and a set of methods annotated with @RequestMapping. Each action calls the matching service operation and adds model attributes for the view. Form submissions bind to the entity through @ModelAttribute. Validation errors return to the same form view with the binding result attached.
@Controller
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService service;
public CustomerController(CustomerService service) {
this.service = service;
}
@GetMapping("/list")
public String list(Model model) {
model.addAttribute("customers", service.findAll());
return "customer/list";
}
}
The generated methods use constructor injection. This keeps the controller easy to test and avoids field injection. If the project uses an older Spring version, change the recipe template once and regenerate the whole layer.
Adjusting the recipe
Open the recipe editor to change the base path, the action names or the view folder. The editor validates the template before it runs. Keep the recipe focused on routing and view selection. Business rules belong in the service layer, where they can be tested without a web container.
/customer and to views under /customer. Consistent names make the generated navigation easy to follow.Related recipes cover the service layer, named queries and validation. Read them together to see how one model change flows through every generated layer.