简体   繁体   中英

Spring MVC REST - Returning xml or json according to request content type

I'm trying to create RESTful Web Service which will return json or xml according to request content type:

My controller looks like this:

@Controller
public class RESTController {

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

My User Class looks like this:

@XStreamAlias("user")
public class User {

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

and finally my Servlet.xml looks like this:

<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>

My problem is that no matter what content type I'm sending i'm always getting JSON response.

在此处输入图片说明

Looks like you need to add

Accept: application/xml

to your request headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM