Spring REST 3支持XML和JSON [英] Spring REST 3 to Support XML and JSON

查看:132
本文介绍了Spring REST 3支持XML和JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们使用Spring MVC开发REST,它将支持XML和JSON数据。我在我的spring config bean中写了ContentNegotiationViewResorver app-servlet.xml

If we develop REST using Spring MVC, it will support XML and JSON data. I have wrote ContentNegotiationViewResorver in my spring config bean app-servlet.xml

<bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
        p:order="1">
        <property name="mediaTypes">
            <map>
                <entry key="xml" value="application/xml" />
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <property name="marshaller">
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller"
                            p:autodetectAnnotations="true" />
                    </property>
                </bean>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
    </bean>

我的春季REST控制器是:

And my spring REST Controller is:

@Controller
@RequestMapping("/rest/customers")
class CustomerRestController {

protected Log log = LogFactory.getLog(CustomerRestController.class);

@RequestMapping(method = POST)
@ResponseStatus(CREATED)
public void createCustomer(@RequestBody Customer customer,
        HttpServletResponse response) {

    log.info(">>>" + customer.getName());
    response.setHeader("Location", String.format("/rest/customers/%s",
            customer.getNumber()));
}


@RequestMapping(value = "/{id}", method = GET)
@ResponseBody
public Customer showCustomer(@PathVariable String id) {
    Customer c = new Customer("0001", "teddy", "bean");
    return c;
}


@RequestMapping(value = "/{id}", method = PUT)
@ResponseStatus(OK)
public void updateCustomer(@RequestBody Customer customer) {
    log.info("customer: " + customer.getName());
}

我设置 @XStreamAlias(customer)<我的客户域类中的/ code>注释。
但是当我尝试访问 http:// localhost:8080 / rest / customers / teddy.xml 时,它总是响应JSON数据。

I set @XStreamAlias("customer") annotation in my customer domain class. But when I try access http://localhost:8080/rest/customers/teddy.xml it always response JSON data.

我在客户域类中设置了 @XmlRootElement(name =customer)注释。
但是当我尝试访问 http:// localhost:8080 / rest / customers / teddy.json 时,它总是响应XML数据。

I set @XmlRootElement(name="customer") annotation in my customer domain class. But when I try access http://localhost:8080/rest/customers/teddy.json it always response XML data.

有什么问题吗?

推荐答案

我认为xml 内容类型应映射到text / xml而不是application / xml。另外,要强制基于扩展名的内容类型解析器,您可以尝试将ContentNegotiatingViewResolver的favorPathExtension属性设置为true(尽管默认情况下它应该是true!)

I think "xml" content type should be mapped to "text/xml" not to "application/xml". Also, to force content type resolvers based on extension, you can try to set the "favorPathExtension" property of "ContentNegotiatingViewResolver" to true(though it should have been true by default!)

编辑:我现在已经在这个GIT位置添加了一个工作样本 - git://github.com/bijukunjummen/mvc-samples.git ,如果你提起端点,使用mvn tomcat:run,json服务于 http:// localhost:8080 / mvc-samples / rest / customers / teddy.json 和xml at 的http://本地主机:8080 / MVC采样/休息/客户/ teddy.xml 。这使用JAXB2而不是XStream,因为我熟悉JAXB。我注意到的一件事是,当我的JAXB注释在Customer类中不正确时,Spring正在按照您看到它的方式提供JSON而不是XML(您可以通过从Customer类中删除XMLRootElement注释来复制它),一旦我修复了我的注释,我按预期得到了XML。 因此可能是您的XStream配置出现问题。

I have now added a working sample at this GIT location - git://github.com/bijukunjummen/mvc-samples.git, if you bring up the endpoint, using mvn tomcat:run, the json is served at http://localhost:8080/mvc-samples/rest/customers/teddy.json and xml at http://localhost:8080/mvc-samples/rest/customers/teddy.xml. This uses JAXB2 not XStream, as I am familiar with JAXB. One thing I noticed was that when my JAXB annotations were not correct in Customer class, Spring was serving out JSON and not XML the way you saw it(You can replicate it by removing the XMLRootElement annotation from Customer class), once I fixed up my annotations, I got back XML as expected. So it could be that there is something wrong with your XStream configuration.

编辑2:你说得对!我没注意到,一旦我回到xml,我认为json现在正在工作。我看到问题,在 AnnotationMethodHandlerAdapter 中,对 @ResponseBody 的处理有点奇怪,它完全忽略了ViewResolvers,并使用已注册的MessageConverters完全绕过 ContentNegotiatingViewResolver ,现在一种解决方法是使用 @ModelAttribute 注释进行响应,而不是@ResponseBody,这样看起来Resolvers被调用。现在尝试使用 git@github.com上的项目:bijukunjummen / mvc-samples.git ,看看它是否适合你。这可能是一个Spring bug,你可以尝试在Spring论坛中提出它并看看他们推荐的内容。

EDIT 2: You are right!! I did not notice, once I got back xml, I assumed that json is working now. I see the problem, in AnnotationMethodHandlerAdapter, the handling for @ResponseBody is a little strange, it completely ignores the ViewResolvers, and uses the registered MessageConverters instead completely bypassing the ContentNegotiatingViewResolver, one workaround for now is to use @ModelAttribute annotation for response, instead of @ResponseBody, this way the view Resolvers are getting called. Try now using the project at git@github.com:bijukunjummen/mvc-samples.git and see if it works for you. This could be a Spring bug, you may try and bring it up in the Spring forum and see what they recommend.

这篇关于Spring REST 3支持XML和JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆