2011-06-08 112 views
3

我有三个资源:如何匹配Spring框架使用@RequestMapping时通配符接受标题

@RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=text/html") 
    public ResponseEntity<String> sampleResourceHtml() 

    @RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=application/xml") 
    public ResponseEntity<String> sampleResourceXml() 

    @RequestMapping(value = "sample", method = RequestMethod.GET, headers = "Accept=application/json") 
    public ResponseEntity<String> sampleResourceJson() 

当HTTP客户端访问的URL以接受= */* web应用程序返回404

在这种情况下,我想调用sampleResourceHtml()

更改"Accept=text/html""Accept=text/html, */*"会让我的web应用程序接受请求,接受= */*这就是我想要的,但它也将接受(Accept)=富/酒吧请求whic h不是我想要的。

如何修改我的代码以返回支持的包含通配符的媒体类型而不返回不支持的请求的意外媒体类型?

回答

2

您可能会发现在AnnotationMethodHandlerAdapter的上下文中更容易配置此选项,以便自动处理标头,而且转换是通过Spring而不是以编程方式完成的。

例如,你可以使用以下配置:

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/> 
    <bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> 
    <constructor-arg ref="xstreamMarshaller"/> 
</bean> 
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="messageConverters"> 
    <util:list> 
     <ref bean="xmlMessageConverter"/> 
     <ref bean="jsonHttpMessageConverter"/> 
    </util:list> 
    </property> 
</bean> 

并修改控制器返回的春天将转换为所需类型的对象。

@RequestMapping(value = "sample", method = RequestMethod.GET) 
public ResponseEntity<String> sampleResource() 

注:您将需要在类路径中的相关库。

+0

我想我将不得不添加@RequestHeader(“接受”)字符串接受作为方法参数和解析头自己。这是我希望通过使用标题注释避免的事情之一。 – Buhb 2011-06-08 13:21:23

+0

根据请求上的_Accept_头,Spring可以返回对象的表示形式。因此,如果我的请求具有'Accept =“application/json”',那么Spring将会在对象中使用简单的'@ RequestMapping'将对象转换为JSON。如果'Accept =“text/xml”',Spring会将对象作为XML返回。 – andyb 2011-06-08 13:26:25

+0

太棒了。我会试试看。 – Buhb 2011-06-08 13:32:56