bro*_*ock 9 java rest spring spring-mvc
我正在使用Spring 3.0 RC1框架,我目前正在测试Spring mvc.我想使用Spring mvc来处理restful请求.我已经设置了我的控制器来处理URI请求.我正在传递xml请求.所以在控制器上我有一个如下方法:
public void request(RequestObject request) {
doSomething();
}
Run Code Online (Sandbox Code Playgroud)
我很难将xml转换为RequestObject.我没有看到太多关于此的文档,我想知道是否有人能指出我正确的方向.我猜你必须使用JAXB或其他东西来注释RequestObject,以告诉Spring将xml文件转换为RequestObject,但我不确定.
感谢您所有的帮助!!
小智 8
要将XML转换为Java对象,可以使用Apache Digest http://commons.apache.org/digester/.Spring在内部使用它.
更新 我不知道Spring 3.0中的这个新功能.对不起您的错误行为.我写了快速测试,这是你应该做的.
1)在-servlet.xml中设置ViewResoler和MessageConverter.在我的测试中它看起来像这样
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean id="person" class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="contentType" value="application/xml"/>
<property name="marshaller" ref="marshaller"/>
</bean>
<oxm:jaxb2-marshaller id="marshaller">
<oxm:class-to-be-bound name="com.solotionsspring.test.rest.model.Person"/>
</oxm:jaxb2-marshaller>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="marshallingHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="marshaller" />
</bean>
Run Code Online (Sandbox Code Playgroud)
2)将XML结构注释添加到Java类中
@XmlRootElement
public class Person {
private String name;
private int age;
private String address;
/**
* @return the name
*/
@XmlElement
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
@XmlElement
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the address
*/
@XmlElement
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
}
Run Code Online (Sandbox Code Playgroud)
3)将映射注释添加到Controller类中
@Controller
public class RestController {
@RequestMapping(value = "/person", method = RequestMethod.PUT)
public ModelMap addPerson(@RequestBody Person newPerson) {
System.out.println("new person: " + newPerson);
return new ModelMap(newPerson);
}
}
Run Code Online (Sandbox Code Playgroud)
希望这会帮助你.
| 归档时间: |
|
| 查看次数: |
17793 次 |
| 最近记录: |