Posts

Showing posts with the label Spring Web Annotations

Spring @ResponseBody Annotation Example

Image
In this section we will learn about  @ ResponseBody  Annotation.   @ ResponseBody   is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header. The @ResponseBody annotation is used at method level or method return type level.  The @ResponseBody constructs the response body as JSON or XML or other media type based on following points.  1. MessageConverter configured in the application.  2. Media-type configured by produces attribute in annotations @RequestMapping , @GetMapping etc.  3. Media-type configured by accept request header.  The @ResponseBody only configures body of response. To set response status code we use @ResponseStatus annotation at method level. If status code is not set explicitly, default status code is set to response. The @ResponseBody is used with @Controller anno

Spring @RequestBody Annotation Example

Image
In this section we will learn about  @RequestBody  Annotation.   @RequestBody   annotation is used to indicating a method parameter should be bind to the body of the HTTP request. Internally, this annotation uses HTTP Message converters to convert the body of HTTP requests to domain objects.  "HTTP message converters are used to convert HTTP request body (either JSON or XML) to Java objects and java objects back to XML or JSON for composing HTTP response" { "name" : "john" , "email" : "john@gmail.in" } Assume that we are sending this JSON in the request body, now inside the controller, we can bind this JSON data to a domain object. @PostMapping ( "/users" ) public void saveUser ( @RequestBody User user ) { } Now this will happen with the help of Jackson API which is present in the classpath. Spring would convert the incoming JSON to a User object from the request body (because we added the  @RequestBody  annotat