Can we send an Object as the response of Controller handler method?
Can we send an Object as the response of Controller handler method?
Yes, you can send an object as the response of a controller handler method in Spring MVC. This is typically done using the @ResponseBody
annotation on the handler method. The @ResponseBody
annotation tells Spring that the return type should be written directly to the HTTP response body, and not placed in a Model, or interpreted as a view name.
When you use @ResponseBody
, Spring uses HTTP Message Converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header. Commonly, this involves converting the return object to JSON or XML format.
For example, if you have a controller method that returns an instance of a User
class, you can annotate this method with @ResponseBody
, and Spring will automatically serialize the User
object into JSON format and write it to the response body:
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public User getUser() {
return new User("John", "Doe");
}
In this example, when the /user
endpoint is accessed, it will return a JSON representation of the User
object. The actual conversion from the User
object to JSON is typically handled by the MappingJackson2HttpMessageConverter
if Jackson is on the classpath[2][9].
Additionally, if you are using Spring 4.1 and above, you can also use the ResponseEntity
object to return the response. ResponseEntity
allows more flexibility as it can contain both the body and the status code, making it useful for finer control over the response details:
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ResponseEntity<User> getUser() {
User user = new User("John", "Doe");
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào