SPRING BOOT @PostMapping
SPRING BOOT
The @PostMapping annotation is commonly used to handle HTTP POST requests in Spring Boot applications.
Spring Boot @PostMapping annotation
➔ The @PostMapping annotation maps with the HTTP POST method, where data can be sent to the Spring RestController. @PostMapping is used to send data to the server, the server receives the data by the post request handler method using the @RequestBody annotation.
Key points of Spring Boot @PostMapping annotation:
➔ The controller class receives data sent by the client and can send the data to be stored permanently in the database after processing.
➔ This annotation performs standard operations such as creating new entities from client data and passing this entity or model to the service layer.
➔ Data is usually received in JSON or XML format, @RequestBody automatically deserializes it into a Java object.
➔ @Postmapping is a recommended alternative to @RequestMapping(method = RequestMethod.POST). Both perform the same function, but @PostMapping is the recommended way to handle HTTP POST requests.
➔ Multiple URLs can be handled in a single method by using a string array in the value or path attribute, for example, @PostMapping(path={"/user","/myuser"}).
Syntax
/* all are equivalent. */
@PostMapping({"/user", "/myuser"}) or
@PostMapping(value={"/user", "/myuser"}) or
@PostMapping(path={"/user", "/myuser"})
➔ The value and path attributes of the @PostMapping annotation are aliases of each other, there is no difference in functionality between them and can be used interchangeably.
Syntax
/* All are equivalent. */
@PostMapping("/client") or
@PostMapping(value = "/client") or
@PostMapping(path = "/client")
@PostMapping supports attributes to match the requested url
➔ params: Narrowing mappings based on the presence, absence, or value of a specific request parameter.
Syntax
Example: @PostMapping(value = "/user", params = "name")
➔ headers: It finds the presence, absence, or value of specific HTTP headers for specific request headers.
Syntax
Example: @PostMapping(value = "/user", headers="name=john")
➔ consumes: This specifies the media types will be consumed by the controller method from the request body.
➔ produces: This specifies the media should be produced and sent to the client as a response by the controller.
Syntax
Example: @PostMapping(value = "/user", produces="application/xml")
Example: @PostMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
Example: @PostMapping(value = "/user", produces = {"application/json", "application/xml"})
@PostMapping handles dynamic URLs using @PathVariable.
➔ For example, @PostMapping("/user/{id}") can work with handlerName(@PathVariable Long id) to handle dynamic URLs.
Request URL is localhost:8090/user/101
Syntax
@PostMapping(value="/user/{id}")
public String userHandler(@PathVariable Long id) {
return "PathVariable is working fine, ID="+id;
}
@PostMapping handles request parameters using @RequestParam.
➔ For example, @PostMapping(/user) can work with handlerName(@RequestParam(name = "name") String name) to handle query parameters.
➔ Parameters can be sent as a query string in the URL or as form data in the body of the HTTP request.
The request URL is localhost:8090/user?name=john
Syntax
@PostMapping(value="/user")
public String userHandler(@RequestParam("name") String n) {
return "RequestParam is working fine, name="+n;
}
Common usage and best practices:
➔ @PostMapping typically accepts data such as a String, a Java object, or a list of Java objects using the @RequestBody annotation, which Spring Boot automatically converts this incoming data (usually JSON or XML) into the appropriate Java format.
➔ @PostMapping typically returns data such as a String, a Java object, or a list of Java objects, which Spring Boot automatically converts to the appropriate response format.
Now practice this chapter in your learning environment.
01 Create a Spring Boot project using Spring Tool Suite (STS).
02 Create a Controller class
Name it anything, for example UserController.
Controller Code
package com.exam.helloworld;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UsersController {
@PostMapping("/users")
public String userHandler(@RequestBody String data) {
return "Data is: " + data;
}
}
03 Run HelloworldApplication.java
After successfully run the application.
Now test the @PostMapping request url in Postman (an API testing tool).
Send JSON object.
Send JavaScript object.
The main syntax differences between JSON and JavaScript object.
➔ JSON: In JSON syntax, keys must be strings enclosed in double quotes e.g. {"name": "John"}.
➔ JavaScript: Keys can be strings (double or single quotes), numbers, or unquoted identifiers in JavaScript object syntax (e.g. {name: "John", 'age': 30, 10: "value"}.
Send Text data.
Example @PathVariable
package com.exam.helloworld;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UsersController {
@PostMapping("/users/{id}")
public String usersHandler(@RequestBody String data, @PathVariable Long id) {
return "Data is: " + data+"\nPathVariable is: "+id;
}
}
@PathVariable with @PostMapping, output
Example @RequestParam
package com.exam.helloworld;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UsersController {
@PostMapping("/users/{id}")
public String usersHandler(@RequestBody String data, @PathVariable Long id,@RequestParam String name) {
return "Data is: " + data+"\nPathVariable is: "+id+"\nRequestParam is: "+name;
}
}
@RequestParam with @PostMapping, output