【问题标题】:Spring MVC REST - Returning xml or json according to request content typeSpring MVC REST - 根据请求内容类型返回 xml 或 json
【发布时间】:2012-08-02 19:01:06
【问题描述】:

我正在尝试创建 RESTful Web 服务,它将根据请求内容类型返回 json 或 xml:

我的控制器如下所示:

@Controller
public class RESTController {

    @RequestMapping(value="/rest/{id}", method=RequestMethod.GET)
    @ResponseBody
    public User getUser(@PathVariable Long id){
        User user = .....
        return user;
    }

我的用户类如下所示:

@XStreamAlias("user")
public class User {

    private long id;
    private String firstName;
    private String lastName; 
      other setters and getters..............
}

最后我的 Servlet.xml 看起来像这样:

<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.vanilla.rest.controllers" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="ignoreAcceptHeader" value="true" />
    <property name="favorPathExtension" value="false" />
    <property name="order" value="1" />
    <property name="mediaTypes">
        <map>
            <entry key="xml" value="application/xml" />
            <entry key="json" value="application/json" />
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <ref bean="xmlView"/>
            <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>

<bean id="xmlView"
      class="org.springframework.web.servlet.view.xml.MarshallingView">
    <property name="contentType" value="application/xml;charset=UTF-8"/>
    <constructor-arg>
        <ref bean="xstreamMarshaller"/>
    </constructor-arg>
</bean>

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="autodetectAnnotations" value="true" />
    <property name="annotatedClass" value="com.vanilla.rest.entities.User"/>
</bean>

我的问题是,无论我发送什么内容类型,我总是收到 JSON 响应。

【问题讨论】:

  • 你在哪里指定一个方法产生什么样的结果?

标签: java xml spring rest spring-mvc


【解决方案1】:

看来你需要添加

Accept: application/xml

到您的请求标头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2012-10-14
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多