liveBook · Manning

@postmapping

As explained in Spring in Action, Sixth Edition

@PostMapping is a Spring MVC annotation that maps HTTP POST requests to a controller method.

@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

How Spring in Action, Sixth Edition covers it

How deep it goes
Works through two handlers, class-level route composition, form binding, and redirects without detailing Spring MVC dispatch internals.
Examples
Uses a taco-design form, its POST handler, and an order-submission handler.
What it assumes
Builds from an HTML POST form and an existing @GetMapping controller, introducing the receiving handler in context.
What you can do after
Apply it via Spring MVC to receive POST form submissions, work with bound objects, and redirect after processing.
How it connects
Connects @RequestMapping and @GetMapping with form binding, @ModelAttribute, and controller redirects.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.