@PostMapping marks a Spring MVC controller method as a handler for HTTP POST requests. Use it when a form sends data to the server, rather than when a page is merely being displayed. Its counterpart, @GetMapping, handles GET requests. section 2.2
Suppose a taco-design form uses method="POST" and has no action attribute. The browser submits its fields to the same /design path that displayed the form. A controller with class-level @RequestMapping("/design") can receive that submission through a method annotated @PostMapping. section 2.2
Listing 2.6 Handling POST requests with @PostMapping
@PostMapping
public String processTaco(Taco taco,
@ModelAttribute TacoOrder tacoOrder) {
tacoOrder.addTaco(taco);
log.info("Processing taco: {}", taco);
return "redirect:/orders/current";
}
The design handler receives submitted fields as a Taco object. It adds that taco to the existing TacoOrder, logs it, and returns a redirect to the current-order page. @ModelAttribute identifies the TacoOrder previously placed in the model. section 2.2
Form field names matter: the design form’s name input and ingredients checkboxes correspond to properties on Taco. @PostMapping selects the receiving method; the submitted values supply its data. section 2.2
Listing 2.10 Handling a taco order submission
@PostMapping
public String processOrder(TacoOrder order,
SessionStatus sessionStatus) {
log.info("Order submitted: {}", order);
sessionStatus.setComplete();
return "redirect:/";
}
The same pattern handles an order submission. With @RequestMapping("/orders") on the controller, @PostMapping receives the order form’s POST request. This handler logs the TacoOrder, marks the session complete, and redirects to the home page. section 2.2
