Spring MVC可以提供restful service,通过@ResponseBody注解可以返回各种数据类型,比如string/json/xml
配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
关于xml类型的配置,网上有通过配置
MarshallingHttpMessageConverter
,但是如果对model对象不加jaxb注解的话,仍然不work,但是,加了注解以后,即使不配置
MarshallingHttpMessageConverter
,仍然可以解析xml,因此,本文不采用
MarshallingHttpMessageConverter
,直接在数据对象上加jaxb注解。
package com.bill.springrest.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable{
private int userId;
private String userName = "";
private String password = "";
@XmlElement
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@XmlElement
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@XmlElement
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName
+ ", password=" + password + "]";
}
}
对于List数据,jaxb没有提供直接的支持,需要进行数据封装
package com.bill.springrest.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "userList")
public class UserList{
private int count;
private List<User> userList;
public UserList() {}
public UserList(List<User> userList) {
this.userList = userList;
this.count = userList.size();
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@XmlElement(name="user")
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
对于rest接口的测试,可以用firefox的restClient插件 https://addons.mozilla.org/zh-CN/firefox/addon/restclient/
在controller中可以通过headers限定可以处理的请求,比如headers="Accept=application/json,application/xml"
controller会根据请求中的header来判断返回的数据格式,比如,请求中是Accept: application/json,那么将返回json对象
例如,发送GET http://127.0.0.1:8080/springrest/rest/user/1.do Accept: application/xml
返回
<user>
</ user >
源码:http://download.csdn.net/detail/sundongsdu/5840955
参考文献:
http://my.oschina.net/615stu/blog/79312
http://www.ibm.com/developerworks/cn/web/wa-spring3webserv/
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/