@PostMapping helps your Spring Boot app listen for POST requests easily. It connects a web address to a method that handles data sent by users.
@PostMapping for POST requests in Spring Boot
@PostMapping("/path")
public ReturnType methodName(@RequestBody DataType data) {
// handle POST request
}The string inside @PostMapping("/path") is the URL path this method listens to.
@RequestBody tells Spring to convert the incoming data (like JSON) into a Java object.
@PostMapping("/submit") public String submitData(@RequestBody String data) { return "Received: " + data; }
@PostMapping("/users") public User createUser(@RequestBody User user) { // save user to database return user; }
This Spring Boot controller listens for POST requests at /greet. It expects a plain text name in the request body and responds with a greeting message.
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @PostMapping("/greet") public String greetUser(@RequestBody String name) { return "Hello, " + name + "!"; } }
Always use @RequestBody to get data from the POST request body.
Make sure your client sends data in the correct format (like JSON or plain text) matching your method parameter.
Use @RestController to make your class ready to handle web requests and return responses directly.
@PostMapping connects a URL path to a method that handles POST requests.
Use it when you want to receive and process data sent by users or clients.
Remember to use @RequestBody to get the data from the request body.