Return to site

๐Ÿƒ๐ŸŽ“ SPRING CERTIFICATION QUESTION: When do you need @ResponseBody?

ยท spring,vcp,java

Answer:

๐‘๐ž๐ฌ๐ฉ๐จ๐ง๐ฌ๐ž๐๐จ๐๐ฒ annotation is a step further from a classic MVC approach to a REST approach

when ๐•๐ข๐ž๐ฐ๐‘๐ž๐ฌ๐จ๐ฅ๐ฏ๐ž๐ซ is not needed and request-handler result might be directly written to the http-response body.

๐‘๐ž๐ฌ๐ฉ๐จ๐ง๐ฌ๐ž๐๐จ๐๐ฒ annotation does exactly that, enabling functionality offered by ๐‡๐ญ๐ญ๐ฉ๐Œ๐ž๐ฌ๐ฌ๐š๐ ๐ž๐‚๐จ๐ง๐ฏ๐ž๐ซ๐ญ๐ž๐ซ message-converters.

Note: ๐‘๐ž๐ฌ๐ฉ๐จ๐ง๐ฌ๐ž๐๐จ๐๐ฒ annotation might be applied at a type level,

thus all handler methods declared within that type will inherit declared behavior.

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

Suppose we have a custom Response object:

Next, the associated controller can be implemented:

In the developer console of our browser or using a tool like Postman, we can see the following response:

{"๐ญ๐ž๐ฑ๐ญ":"๐“๐ก๐š๐ง๐ค๐ฌ ๐…๐จ๐ซ ๐๐จ๐ฌ๐ญ๐ข๐ง๐ !!!"}

 

Remember, we don't need to annotate the @RestController-annotated controllers with the @ResponseBody annotation since Spring does it by default.

#spring #certificationquestion #vcp