REST Service即REST(Representational State Transfer表述性状态转移)是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。因此,在许多系统的开发中都需要搭建REST Service。本文我们就来说说如何用Spring MVC搭建REST Service。
随着互联网技术的兴起,XML越来越令人诟病,XML的数据包越来重,SOAP协议方便性和灵活性都有欠缺,尤其兴起的Web2.0发展,由Yahoo、Google 和 Facebook等大型互联网公司的倡导,REST代表性状态传输(Representational State Transfer,REST)在 Web 领域已经得到了广泛的接受,是基于 SOAP 和 Web 服务描述语言(Web Services Description Language,WSDL)的 Web 服务的更为简单的替代方法。下面是Spring MVC搭建REST Service的大概流程。
1.配置pom.xml
pom.xml的配置由于代码量庞大,且是固定的配置,可以自行在网上查阅拷贝。
2.配置web.xml
配置代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:root-context.xml</param-value>
</context-param>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:servlet-context.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3. servlet-context.xml (关键配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.cnblogs.yjmyzz" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="favorParameter" value="false" />
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="text/html" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean id="xmlView"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.cnblogs.yjmyzz.dto.UserInfo</value>
<value>com.cnblogs.yjmyzz.dto.ListBean</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
</beans>
4.DTO对象
package com.cnblogs.yjmyzz.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.cnblogs.yjmyzz.utils.DateUtil;
import com.cnblogs.yjmyzz.utils.ListUtil;
@XmlRootElement(name = "user")
public class UserInfo implements Serializable {
private static final long serialVersionUID = -5461373449802431627L;
private String userName;
private BigDecimal salary;
private Date birthday;
private boolean isVip;
private int id;
private ListBean hobbies;
@XmlElement
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@XmlElement
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@XmlElement
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@XmlElement
public boolean isVip() {
return isVip;
}
public void setVip(boolean isVip) {
this.isVip = isVip;
}
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public ListBean getHobbies() {
return hobbies;
}
public void setHobbies(ListBean hobbies) {
this.hobbies = hobbies;
}
public String toString() {
return "id:" + this.id + ",userName:" + this.userName + ",isVip="
+ this.isVip + ",birthday="
+ DateUtil.formatDate(this.birthday) + ",hobbies:"
+ ListUtil.getString(this.hobbies.getList());
}
}
为了实现List的XML序列化,还需要一个辅助类ListBean
5.Controller
package com.cnblogs.yjmyzz.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cnblogs.yjmyzz.dto.ListBean;
import com.cnblogs.yjmyzz.dto.UserInfo;
import com.cnblogs.yjmyzz.service.UserService;
@Controller
@RequestMapping(value = "/rest", method = RequestMethod.GET)
public class RestController {
@Autowired
UserService userService;
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public UserInfo show(@PathVariable int id, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return userService.getUserInfo(id);
}
@RequestMapping(value = "/user/list", method = RequestMethod.GET)
public ListBean getAll() throws Exception {
return userService.getAllUsers();
}
}
上面详细地介绍了Spring MVC搭建REST Service的各个配置情况,按照上述的合理配置就可以成功的用Spring MVC搭建REST Service。Rest Service 相比Web Service建议的标准更轻量级,甚到用Java script都可以调用,使用方更方便、高效、简单。
QCode09-04 14:38
Code大师09-04 14:50
不写代码你养我啊08-23 11:14
不写代码你养我啊09-17 18:02
要学习了06-18 18:13