2013-08-12 3 views
14

Wenn eine Anfrage ohne Accept-Header an meine API gesendet wird, möchte ich JSON zum Standardformat machen. Ich habe zwei Methoden in meinem Controller, eine für XML und eine für JSON:Wie wird der Standard-Inhaltstyp in Spring MVC in no Accept-Header festgelegt?

@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. 
} 

Wenn ich eine Anfrage ohne Accept-Header senden die getXmlData Methode aufgerufen wird, das ist nicht das, was ich will. Gibt es eine Möglichkeit, Spring MVC mitzuteilen, die Methode getJsonData aufzurufen, wenn kein Accept-Header bereitgestellt wurde?

EDIT:

Es gibt ein defaultContentType Feld in der ContentNegotiationManagerFactoryBean dass der Trick funktioniert.

+2

Wenn Sie habe eine Lösung gefunden mit 'ContentNegotiationManagerFactoryBean' füge es als Lösung hinzu. –

Antwort

11

Wenn Sie Feder 3.2.x verwenden, nur fügen Sie diese feder mvc.xml

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> 
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> 
    <property name="favorPathExtension" value="false"/> 
    <property name="mediaTypes"> 
     <value> 
      json=application/json 
      xml=application/xml 
     </value> 
    </property> 
    <property name="defaultContentType" value="application/json"/> 
</bean> 
+0

Ich habe dies in meine Servlet-context.xml und es funktionierte perfekt. Danke @Larry Z. – UpAllNight

+0

es funktioniert bei mir 2 !!! thx – Rugal

+0

Hat die Einstellung 'mediaTypes' einen Effekt, wenn' favorPathExtension' auf 'false' gesetzt ist? – holmis83

15

Vom Spring documentation, können Sie dies wie folgt mit Java Config tun:

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