Srinivas Bala
Srinivas Bala

Reputation: 21

How the request body of form is passed to spring mvc controller and how to map to pojo class instance?

How the request body of form is passed to the spring MVC controller and how to map to the POJO class instance?

Upvotes: 1

Views: 977

Answers (3)

Swaroop Aaleti
Swaroop Aaleti

Reputation: 41

I presume, you are building end point using POST. If yes, you can annotate method parameter with @RequestBody to a capture request body.

Basically, @RequestBody is used to bind the HTTP request body with a domain object in method parameter. Behind the scenes, these annotation uses HTTP Message converters to convert the body of HTTP request to domain objects.

@RequestMapping(value="/user/create", method=RequestMethod.POST)
public void createUser(@RequestBody User user){
 // your logic goes here..
 // Make sure that parameters in User POJO matches with HTTP Request Parameters.
}

Upvotes: 3

Pratham Krishna
Pratham Krishna

Reputation: 1

Let's say you're doing a POST request.

@PostMapping
public void saveSomeData(@RequestBody PojoClass pojoClass){
    // whatever you wanna do
}

The @RequestBody annotation extracts the data your client application is sending on the body of the request. Also, you'd want to name the member variables on your pojo class similar to how you named it in on your request body.

Your POJO class can be something like:

public class PojoClass{
   private String name;
   private int age;
}

Now you can create getters and setters or use the Lombok annotation @Data on the class level to auto-generate the getters and setters.

Hope this was helpful:)

Upvotes: 0

Kumaresh Babu N S
Kumaresh Babu N S

Reputation: 1698

I assume you are using POST API request for your use case. In the spring mvc controller class, we can make use of @RequestBody annotation followed by Pojo class.

Example:

@PostMapping
public ResponseEntity<ResponseDto> saveData(@RequestBody Data data) {
  // Access to service layer
}

Upvotes: 0

Related Questions