DEV Community

Cover image for Spring - @RequestBody and @ResponseBody
Yiğit Erkal
Yiğit Erkal

Posted on

Spring - @RequestBody and @ResponseBody

@RequestBody

Annotation indicating a method parameter should be bound to the body of the HTTP request. With the @RequestBody annotation, POST or PUT requests are handled. It is generally used to convert a request into an object in JSON or XML format.

RequestBody Spring Annotation

For example:

@RequestMapping(value = "/isConverted", method = RequestMethod.POST)
@ResponseBody
public String isConvertedFromJson(@RequestBody User user) {
    return user.getUserName();
}
Enter fullscreen mode Exit fullscreen mode

@ResponseBody

It can be put on a method and indicates that the return type should be written straight to the HTTP response body. Not placed in a Modal or View name. With the @ResponseBody annotation, we can return values ​​of multiple types such as String, application/json or application/xml.

ResponseBody Spring Annotation

For example:

@RequestMapping(value = "/produceString", method = RequestMethod.GET)
@ResponseBody
public String produceString() {
     return "Hello World";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)