@RequestBody and @ResponseBody annotations

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest onto a Java object.

The example below shows how @RequestBody annotation works

@PostMapping("/request")
public ResponseEntity postController(@RequestBody LoginForm loginForm) {
    exampleService.fakeAuthenticate(loginForm);
    return ResponseEntity.ok(HttpStatus.OK);
}
...
public class LoginFOrm {
    private String username;
    private String password;
}

Spring automatically deserializes the JSON into a Java type assuming an appropriate one is specified. By default, the type annotated with the @RequestBody annotation must correspond to the JSON sent from client-side controller. In this case JSON is like: {“username”: “johnny”, “password”: “password”}

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object. Let’s look at the code snippet below :

public class ResponseTransfer {
    private String text;

    // getters and setters
}
...
@Controller
@RequestMapping("/post")
public class ExamplePostController {
    
    @PostMapping("/response")
    @ResponseBody
    public ResponseTransfer postResponseController(@RequestBody LoginForm 
      loginForm) {
        return new ResponseTransfer("Thanks For Posting!!!");
}

The response will be the following : {“text”:”Thanks For Posting!!!”}

Next

Leave a Reply

Your email address will not be published. Required fields are marked *