如何强制spring的@ResponseBody使用xmlConvertor [英] How to force spring's @ResponseBody to use xmlConvertor

查看:324
本文介绍了如何强制spring的@ResponseBody使用xmlConvertor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从这样的控制器返回单个对象时,

When I return a single object from a controller like this,

@ResponseBody 
public MyClass module(...) {
...
}

我得到xml输出在客户端和这样的日志显示,

I get the xml output on the client and log shows like this,


2011-09-07 18:22:06,963 [qtp1409490836-27] DEBUG
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
- 使用
[org.springframework]将[com.domain.MyClass@4374820d]写为application / xhtml + xml
.http.converter.xml.Jaxb2RootElementHttpMessageConverter @ b4e1f3]

2011-09-07 18:22:06,963 [qtp1409490836-27] DEBUG org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - Written [com.domain.MyClass@4374820d] as "application/xhtml+xml" using [org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@b4e1f3]

但如果我使用这样的列表,

But If I use a list like this,

@ResponseBody 
public List<MyClass> module(...) {
...
}

它使用jsonConvertor并返回json输出。

It uses jsonConvertor and returns the json output.


2011-09-07 18:38:31,026 [qtp420370595-26] DEBUG
org .springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
- 使用
将[[com.domain.MyClass@654309f0]]写为
application / json; charset = UTF-8 [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@14419f80]

2011-09-07 18:38:31,026 [qtp420370595-26] DEBUG org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - Written [[com.domain.MyClass@654309f0]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@14419f80]

MyClass用jaxb注释。在球衣中,我可以说

The MyClass is annotated with jaxb. In jersey I could say

@Produces({ MediaType.APPLICATION_XML })

如何强制spring始终使用xmlconverter?

How do I force spring to use the xmlconverter always?

推荐答案

有一些错误意味着您无法在列表中返回您的班级。您需要创建一个新类来保存对象列表并在@ResponseBody中返回它。这样的事情:

There is some bug that means you cannot return your class in a list. You need to create a new class to hold your list of objects and return that in the @ResponseBody. Something like this:

@RequestMapping(value = Constants.URL, method = RequestMethod.GET)
public @ResponseBody ListHolder getFoos(HttpServletResponse response) {
    response.setContentType("application/xml");         
    List<Foo> foos = getFoos(); 
    ListHolder listHolder = new ListHolder();
    listHolder.setFoos(foos);
    return listHolder;
}

使用@XmlRootElement注释ListHolder类,如果你有jaxb jar或Java 6然后它应该工作。

Annotate your ListHolder class with @XmlRootElement and if your have the jaxb jar or Java 6 then it should work.

这篇关于如何强制spring的@ResponseBody使用xmlConvertor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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