seal
seal

Reputation: 1143

Post request not bind data with POJO class in spring mvc Rest api.

I am very new to rest api concept. I am trying to implement a simple method that can receive a post method. The problem is request hit the method but the not bind the data with the POJO class. Here is the my code.

@RestController
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

@ResponseBody
@RequestMapping(value = "/", method = RequestMethod.POST)
public CompileRequest home(@ModelAttribute CompileRequest compileRequest) {
    logger.info("user name : {}", compileRequest.getUserName()); // null
    logger.info("input file path : {}", compileRequest.getInputFilePath()); //null
    return compileRequest;
}
}

I did not use @RequestBody because it gives me 415 http error. And this is my POJO class.

@Data // use lombok for getter and setter. 
public class CompileRequest {
   private String userName;
   private String inputFilePath;
}

POSTMAN view

The userName and inputFilePath field is remaining null. I am not understand why not the data binding is not working. How can I fix this ?

Thank you.

Upvotes: 1

Views: 1213

Answers (1)

LynAs
LynAs

Reputation: 6537

Use the return as following. Since u want rest response it also gives you option to send proper status code

public ResponseEntity<?> home(@RequestBody CompileRequest compileRequest) {

   return return ResponseEntity.ok(compileRequest);
}

add the following on top of CompileRequest class

@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor(access = AccessLevel.PUBLIC)

Also add the following dependency if you don't have it already

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson}</version>
        </dependency>

Finally send data as Json

{

   "userName" : "name",
   "inputFilePath": "path"

}

Upvotes: 3

Related Questions