Return to site

🍃🎓 SPRING CERTIFICATION QUESTION: When do you need @ResponseBody?

January 28, 2023

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