Spring MVC — Sending Responses
In this lesson, we'll recap how to send HTTP responses from our application.
Sending Response Body
The return value of a handler method in a RestController becomes the body of the response. Java objects, maps, collections or arrays would be converted to JSON by Spring Boot by default. If you want to send plain text, return a string.
See Spring Lemon's LemonController for some examples.
If you're using @Controller instead of @RestController, don't forget to annotate handler methods with @ResponseBody (otherwise Spring MVC will assume the return value as the view name).
Sending Status Code
By default, the status code of the responses would be 200. To alter it, you can use the @ResponseStatus annotation. For example, the ping method below would respond with a 204 status code.
Sometimes you may need more power. For example, you may need to alter the status code dynamically, or maybe send some response headers. Returning a ResponseEntity is handy in such cases. See it's JavaDoc for some examples.
Accessing the underling HttpServletResponse object
The JavaEE servlet framework uses an HttpServletResponse object to compile and send a response. Sometimes you may like to access it, e.g. to add a header. To access it, just pass it as a parameter to the handler method. Here is an example:
So, these are the common ways to sending responses from our handlers.
But, how to receive request data? Join me in the next lesson to discuss that.