Spring MVC 3:通过@ResponseBody返回XML [英] Spring MVC 3: Returning XML through @ResponseBody
问题描述
请原谅我发布这个noob问题,但我现在已经调试了这个问题很长一段时间了。我在尝试获取响应以基于对象返回XML时遇到一些问题: -
Pardon me for posting this noob question, but I have been debugging this problem for quite awhile now. I'm having a little problem trying to get the response to return the XML based on the object:-
@RequestMapping(value = "/mylink", method = RequestMethod.GET)
public @ResponseBody SomeObject doIt() {
...
}
现在,即使调用该API,我的客户端也根本不会收到XML响应。我一直在阅读一些地方,似乎我需要配置XML marshaller或一些XML解析器,但我不确定如何将该部分集成到我现有的配置中。我目前在servlet.xml中有以下配置: -
Right now, even though that API is called, my client side does not receive the XML response at all. I have been reading a few places and it seems like I need to configure the XML marshaller or somesort of XML resolvers, but I'm not sure how to integrate that piece into my existing configuration. I currently have the following configuration in my servlet.xml:-
<context:component-scan base-package="ss.controller" />
<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/app/" />
<property name="suffix" value=".jsp" />
</bean>
有人可以发布一些示例配置,说明如何配置我的servlet.xml以获取这工作?非常感谢。
Can someone kindly post some sample configurations on how I might go about in configuring my servlet.xml to get this working? Thanks much.
推荐答案
这可以通过在Spring上下文中添加以下魔法来实现(参见 docs ):
This can be done by adding the following bit of magic to the Spring context (see docs):
<mvc:annotation-driven/>
除其他外,提供:
如果类路径中存在JAXB,则支持读写XML。
Support for reading and writing XML, if JAXB is present on the classpath.
如果检测到JAXB (即如果您使用的是Java6,或者在类路径上有一些JAXB实现),这将使用上下文注册 Jaxb2RootElementHttpMessageConverter
,并提供吐出的能力来自 @ResponseBody
-annotated方法的返回值的XML。
If JAXB is detected (i.e. if you're on Java6, or otherwise have some JAXB implementation on your classpath), this will register a Jaxb2RootElementHttpMessageConverter
with the context, and will provide the ability to spit out XML from the return value of the @ResponseBody
-annotated method.
注意:您的问题排序建议使用用于呈现XML的 ViewResolver
,但这不是必需的。 @ResponseBody
注释旨在完全绕过视图层。
Note: Your question sort-of suggested using a ViewResolver
for rendering the XML, but this isn't necessary. The @ResponseBody
annotation is designed to bypass the view layer altogether.
这篇关于Spring MVC 3:通过@ResponseBody返回XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!