如何解组到不同的@RequestBody对象类型?

时间:2013-01-08 11:56:13

标签: web-services spring spring-mvc unmarshalling

我在我的Web服务中使用Spring,它接收XML作为输入。它可以是嵌入在HTTP请求中的XML,也可以是 request 属性中的纯文本。

目前我的Web服务正在处理两种不同的XML模式,因此我的unmarshaller可以将XML文件解组为两种对象类型(例如:Foo和Bar)。

在我的Controller中,我有下一个处理请求属性的代码:

@RequestMapping(value={"/mypath"}, method={RequestMethod.POST}, headers={"content-type=application/x-www-form-urlencoded"})
@ResponseBody
public ResponseObject getResponse(@RequestParam("request") String request, HttpServletRequest req) {

它完美地工作,我可以将请求字符串解组为Foo对象或Bar对象。

问题来自XML嵌入:

@RequestMapping(value={"/mypath"}, method={RequestMethod.POST}, headers={"content-type=text/xml"})
@ResponseBody
public ResponseObject getResponse(@RequestBody Foo request, HttpServletRequest req) {

@RequestMapping(value={"/mypath"}, method={RequestMethod.POST}, headers={"content-type=text/xml"})
@ResponseBody
public ResponseObject getResponse(@RequestBody Bar request, HttpServletRequest req) {

这里是MessageConverter:

<bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <property name="marshaller" ref="jaxb2Marshaller" />
    <property name="unmarshaller" ref="jaxb2Marshaller" />
</bean>
<oxm:jaxb2-marshaller id="jaxb2Marshaller" contextPath="path.to.Foo:path.to.Bar"/>

我认为MessageConverter应该自动执行unmarshall但我收到下一个错误:

  

java.lang.IllegalStateException:为HTTP路径'/ws/mypath.ws'映射的不明确的处理程序方法:[...]如果您打算在多个方法中处理相同的路径,那么将它们分解为专用的处理程序具有在类型级别映射的路径的类!

如何自动解组到不同的@RequestBody对象类型? (使用相同的 Web服务路径

1 个答案:

答案 0 :(得分:0)

@RequestMapping中必须有一些东西使每个请求方法都是唯一的,在你的情况下,基于xml的请求映射完全相同 - 在框架找到正确的参数之后计算出参数的类型@RequestMapping的方法。所以你所说的基本上是不可行的,除非你在注释中有更多的东西来帮助框架找到正确的方法。

如果您使用的是Spring 3.1 +,则可以进行以下简化:

@RequestMapping(value={"/mypath"}, method={RequestMethod.POST}, consumes=text/xml)