0
0
Spring Bootframework~5 mins

@PostMapping for POST requests in Spring Boot

Choose your learning style9 modes available
Introduction

@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.

When a user submits a form with data to save or process.
When you want to create a new record in a database via a web request.
When your app needs to receive JSON data from a client.
When you want to handle file uploads from a web page.
When you want to trigger an action that changes data on the server.
Syntax
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.

Examples
Handles POST requests to /submit and returns a confirmation message with the received data.
Spring Boot
@PostMapping("/submit")
public String submitData(@RequestBody String data) {
    return "Received: " + data;
}
Receives a User object in JSON, saves it, and returns the saved user.
Spring Boot
@PostMapping("/users")
public User createUser(@RequestBody User user) {
    // save user to database
    return user;
}
Sample Program

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.

Spring Boot
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 + "!";
    }
}
OutputSuccess
Important Notes

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.

Summary

@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.