如何使用看起来像这样的xml:
<request>
<User>
<name>name value</name>
<age>13</age>
</User>
</request>
然后我可以将其反序列化为具有匹配属性的User对象。
public class User {
private String name;
private Integer age;
// getter and setters
}
有什么简单的我可以做或者我必须手动解析xml吗?
我正在使用spring mvc,这是一个发布xml的方法。
答案 0 :(得分:3)
您的控制器方法应采用User
类型的参数,该参数使用@RequestBody
进行注释。然后,您需要使用适当的marshaller / unmarshaller配置MarshallingHttpMessageConverter
。一个例子,直接来自参考指南:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="stringHttpMessageConverter"/>
<ref bean="marshallingHttpMessageConverter"/>
</util: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="castorMarshaller" />
<property name="unmarshaller" ref="castorMarshaller" />
</bean>
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
有关详细信息,请参阅参考指南中的"Supported method argument types"和"Mapping the request body with the @RequestBody annotation"。
答案 1 :(得分:0)
您可以使用摘要。 它会将您的XML元素绑定到您的POJO。 这是一个完整的教程: http://onjava.com/pub/a/onjava/2002/10/23/digester.html