Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default content type in Spring MVC in no Accept header is provided?

If a request is sent to my API without an Accept header, I want to make JSON the default format. I have two methods in my controller, one for XML and one for JSON:

@RequestMapping(method = RequestMethod.GET,produces=MediaType.APPLICATION_ATOM_XML_VALUE) @ResponseBody public ResponseEntity<SearchResultResource> getXmlData(final HttpServletRequest request) {      //get data, set XML content type in header.  }   @RequestMapping(method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)  @ResponseBody  public ResponseEntity<Feed> getJsonData(final HttpServletRequest request){       //get data, set JSON content type in header.    } 

When I send a request without an Accept header the getXmlData method is called, which is not what I want. Is there a way to tell Spring MVC to call the getJsonData method if no Accept header has been provided?

EDIT:

There is a defaultContentType field in the ContentNegotiationManagerFactoryBean that does the trick.

like image 280
user86834 Avatar asked Aug 12 '13 14:08

user86834


People also ask

What is default controller in Spring MVC?

The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features.

What is Content Negotiation and how we can achieve it in spring boot?

There are two ways to generate output using Spring MVC: You can use the RESTful @ResponseBody approach and HTTP message converters, typically to return data-formats like JSON or XML. Programmatic clients, mobile apps and AJAX enabled browsers are the usual clients.

What is spring mvc4?

Spring MVC is a Model-View-Controller(MVC) web framework build on notion of a central Front Controller servlet (DispatherServlet) which is responsible for dispatching each request to appropriate handlers, resolving views and finally returning the response.


1 Answers

From the Spring documentation, you can do this with Java config like this:

@Configuration public class WebConfig extends WebMvcConfigurerAdapter {   @Override   public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {     configurer.defaultContentType(MediaType.APPLICATION_JSON);   } } 

If you are using Spring 5.0 or later, implement WebMvcConfigurer instead of extending WebMvcConfigurerAdapter. WebMvcConfigurerAdapter has been deprecated since WebMvcConfigurer has default methods (made possible by Java 8) and can be implemented directly without the need for an adapter.

like image 161
RustyTheBoyRobot Avatar answered Sep 28 '22 12:09

RustyTheBoyRobot