【问题标题】:Spring MVC 3.2: returning Document (xml) with @ResponsebodySpring MVC 3.2:使用@Responsebody 返回文档(xml)
【发布时间】:2014-10-22 11:13:35
【问题描述】:

我是 Spring MVC 的新手,我有一个通常返回 org.w3c.dom.Document 对象(XML 文档)的应用程序。该文档有很多不同的(和动态的)结构(没有特定的 xsd)。我需要知道如何从我的控制器返回这些对象。例如

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Document createFOO(Document myDoc){

 return myDoc;
}

当我尝试这样做时,我得到了 HTTP 406 错误,显然我需要一个配置,但我找不到解决我的问题的文档,因为在所有这些解决方案中都包括类和 XML 之间的映射,但是在在我的情况下,该对象已经是一个 XML Doc。你能给我一个指导我的调查吗?

谢谢!

马科斯

编辑:这是我的配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="my.files"/>
    <mvc:annotation-driven/>

</beans>

我的示例类:

@Controller
@RequestMapping("blabla")

public class MyClass{

...

    @RequestMapping(method = RequestMethod.POST, produces = "application/xml")
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public Document myMethod(...) {

        Document responseDoc = foo.giveMeaDocument();
    }
}

【问题讨论】:

  • 您可能在 @RequestMapping 注释中缺少 produces 属性。就像@RequestMapping(produces = "application/xml") 一样,当然,就像你说的那样,你需要在 spring 中配置/依赖项来注册一个合适的 XML 转换器。使用它,您可以返回一个 POJO,它不像 XML 文档那样专门化。
  • 谢谢。哪种转换器应该与这种回报一起使用?
  • 是的,JAXB2 基础架构配置的东西少了,就是OXM……POJO 到XML 的转换类型是谁做的?
  • 同理,ORM 需要 POJO 中的注解,OXM (JAXB2) 也有其他设置。

标签: java xml spring spring-mvc


【解决方案1】:

HTTP/406 错误是由于文档对象无法映射到响应正文。

您需要确保在 XML 配置中使用 或 JavaConfig 样式下的类似结构。

编辑

我已经实现了一个快速且非常脏的应用程序来演示我在说什么:

https://github.com/djgraff209/domconversion

看看这是否满足您的需求 - 请注意,它非常粗糙,仅用于演示技术。

【讨论】:

  • 感谢您的回答:是的,我的应用程序上下文中有
  • 组件扫描与 mvc:annotation-driven 不同。注释驱动设置处理程序以使用 @RequestBody/@ResponseBody 注释编组 JSON、XML 等。
  • 哦,好的。所以我不知道。我认为,由于我成功地将 @ResponseBody 与 String 一起使用(在其他控制器中),所以问题不存在。另外,我需要一个 xml 转换器吗?如果是:为什么?因为 Document 对象是一个 XML。非常感谢您的回复!
  • 如果你添加注解驱动,它应该使用 JVM 默认处理自动绑定它
  • 我试过了,但问题还没有解决。我的代码是这样的:@RequestMapping(method = RequestMethod.POST,produces = "application/xml") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Document createFOO(...) { ... return aDocument; } 但是 406 错误仍然存​​在。
猜你喜欢
  • 2011-06-18
  • 1970-01-01
  • 2013-06-21
  • 2023-03-19
  • 2013-03-08
  • 2023-03-29
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多