Question

I am using Spring MVC 4 and I want to know that I am using @RestController at class level and for one of its method I am Using @RequestMapping(headers = "Accept=application/json"). Now can any one tell me why just by using <mvc:annotation-driven /> in my config-servlet.xml how I am getting the response in JSON on my browser. I mean using header attribute is only saying that this method can only respond to requests having this type of headers. How does the MVC4 knows to respond in JSON on browser. Here is my code:

My config-servlet.xml

<beans>
<context:component-scan base-package="com.songs.service.controller" />
<mvc:annotation-driven />
</beans>

My RestController Class

@RestController
@RequestMapping("/songappWS")
public class SongServiceWS 
{ 
@RequestMapping(value = "/topmoviesWS", method = RequestMethod.GET, headers="Accept=application/json")
public List<?> getTopMoviesWS() {
//method logic
return l1;

}
}
Was it helpful?

Solution

The reason Spring is responding in JSON is that @RestController implicitly means that the the response of getTopMoviesWS() method is handled as if it had the @ResponseBody annotation (already present in Spring 3).

What that means is that Spring will use the Jackson JSON library (if present on the classpath) to convert the response to JSON.

Check out this post.

OTHER TIPS

You get the response in JSON because of @RestController, How??

  1. @RestController is itself annotated with @Controller and @ResponseBody implying that @RequestMapping methods assume @ResponseBody semantics by default.You can have more information here.

To be more comprehensive, your code will look like this :

@RequestMapping(value = "/topmoviesWS", method = RequestMethod.GET, 
  headers="Accept=application/json")   
public @ResponseBody List<?> getTopMoviesWS() { 

   return l1;    
}
  1. the @ResponseBody annotation on the getTopMoviesWS() method tells Spring MVC that it does not need to render the response through a server-side view layer, but that instead the list returned is the response body, and should be written out directly to the HTTP response as JSON. The list returned must be converted to JSON, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the values to JSON. You can have a look here to understand the @ResponseBody mechanism.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top