春季3:内容谈判

时间:2013-12-20 22:53:11

标签: spring-3 restful-architecture

我有一个REST端点,它当前返回JSON输出。我想修改相同的端点以返回纯文本输出,基本上区分生成application/jsontext/plain Accept标头。这是我目前的配置 -

servlet.xml中:                                                                                                         

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="defaultContentType" value="application/json" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="order" value="0" />
    <property name="mediaTypes">
        <map>
            <entry key="text" value="text/plain" />
            <entry key="json" value="application/json" />
        </map>
    </property>

    <property name="defaultViews">
        <list>
            <ref bean="jsonView"/>
        </list>
    </property>
</bean>

<bean id="jsonView"
      class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="contentType" value="application/json;charset=UTF-8"/>
    <property name="disableCaching" value="false"/>
</bean>

REST端点:

@RequestMapping(value = "/emps", method = RequestMethod.GET, produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody List<Employee> getEmpsList() throws VMException {
    final List<Employee> eList = getAllEmployees();
    return eList;
}

我尝试将修改修改为{"application/json", "text/plain"}。通读一些在线内容,因为我要返回一个bean,我需要使用HttpMessageConverter返回text/plain输出。我能够通过编写两个方法来完成这项工作,一个返回application/json输出和其他返回text/plain输出。是否可以将其组合到单个方法实现中,或者更重要的是,根据请求的输出格式返回结果,即jsontext

提前感谢您的帮助。

更新:附加邮递员客户端插件的图片。

图片1: Image1 图2: Image2

1 个答案:

答案 0 :(得分:0)

目前你有这个:

<property name="ignoreAcceptHeader" value="true" />

实际上,您不希望忽略Accept标头。删除它,看看会发生什么。

此外,mediaTypes仅在您通过扩展/格式寻求资源时才有意义,而这似乎并非如此。