简体   繁体   English

如何强制spring的@ResponseBody使用xmlConvertor

[英]How to force spring's @ResponseBody to use xmlConvertor

When I return a single object from a controller like this, 当我从这样的控制器返回单个对象时,

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

I get the xml output on the client and log shows like this, 我在客户端上获得了xml输出,并且日志显示如下:

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] 2011-09-07 18:22:06,963 [qtp1409490836-27]调试org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter-将[com.domain.MyClass@4374820d]编写为“ application / xhtml + xml”,使用[ org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@b4e1f3]

But If I use a list like this, 但是如果我使用这样的列表,

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

It uses jsonConvertor and returns the json output. 它使用jsonConvertor并返回json输出。

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] 2011-09-07 18:38:31,026 [qtp420370595-26]调试org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter-写为[[com.domain.MyClass@654309f0]]为“ application / json; charset = UTF-8”,使用[org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@14419f80]

The MyClass is annotated with jaxb. MyClass带有jaxb注释。 In jersey I could say 在球衣上我可以说

@Produces({ MediaType.APPLICATION_XML })

How do I force spring to use the xmlconverter always? 如何强制spring始终使用xmlconverter?

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. 您需要创建一个新类来保存对象列表,并将其返回到@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;
}

Annotate your ListHolder class with @XmlRootElement and if your have the jaxb jar or Java 6 then it should work. 用@XmlRootElement注释ListHolder类,如果您具有jaxb jar或Java 6,则它应该可以工作。

If Spring cant find a JSON convert it can't send JSON. 如果Spring找不到JSON转换,它将无法发送JSON。 Try to remove jackson.jar from the class path and it should default to XML through XStream for all request. 尝试从类路径中删除jackson.jar,并且对于所有请求,它都应默认通过XStream设置为XML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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