如何使用Spring MVC3在REST中执行JAXB2输入请求编组?

时间:2012-06-28 08:29:28

标签: rest spring-mvc

我是Spring MVC(Spring 3)和REST的新手,我正在尝试一个小玩具应用程序来尝试GET和POST Web服务。我已经阅读了Spring的官方参考资料,并在Stackoverflow RequestBody of a REST applicationPass a request parameter in Spring MVC 3中发现了这些问题,但我仍然坚持使其成功。任何人都可以给我一些我错过的提示吗?

我的控制器是这样的:

@Controller
@RequestMapping(value = "/echo")
public class EchoControllerImpl implements EchoController {
    @RequestMapping(method = RequestMethod.POST, value = "/echoByPost")
    public ModelAndView echoByPost(@ModelAttribute EchoDto input) {
        // ... 
    }
}

我在app ctx:

中推出了相应的转换器
<mvc:annotation-driven />
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" >
    <property name="classesToBeBound">
        <list>
            <value>foo.EchoDto</value>
        </list>
    </property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="marshallingHttpMessageConverter" />
            <ref bean="stringHttpMessageConverter" />
        </list>
    </property>
</bean>

<bean id="stringHttpMessageConverter"
    class="org.springframework.http.converter.StringHttpMessageConverter" />

<bean id="marshallingHttpMessageConverter"
    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <property name="marshaller" ref="jaxb2Marshaller" />
    <property name="unmarshaller" ref="jaxb2Marshaller" />
</bean>
<!-- other beans like ViewResolvers  -->

我甚至尝试将这些添加到web.xml中,因为我看到某处提到它(虽然我真的不知道它意味着什么)

<filter>
    <filter-name>httpPutFormFilter</filter-name>
    <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>httpPutFormFilter</filter-name>
    <servlet-name>spring-rest</servlet-name>
</filter-mapping>

然后我尝试通过Curl调用我的Web服务: curl -d "echoDto=<EchoDto><message>adrian</message></EchoDto>" http://localhost:8001/foo/rest/echo/echoByPost.xml

我发现我的传入对象不是通过解组JAXB2创建的。相反,似乎调用了包含整个请求xml消息的ctor EchoDto(String)。

(我也尝试用@RequestBody注释参数,但更糟糕的是,我甚至无法调用控制器方法)

有人能告诉我我错过了什么吗?

使用DTO类正确设置了Jaxb2Marshaller,因为我可以在另一个GET REST webserivce调用的情况下将其用作返回的模型对象。

1 个答案:

答案 0 :(得分:1)

您需要设置请求的内容类型,而不需要echoDto=

curl -H "Content-Type: application/xml" -d "<EchoDto><message>adrian</message></EchoDto>" http://localhost:8001/foo/rest/echo/echoByPost.xml