Spring Restful Web服务教程:JSON与Jackson客户端开发实例
Spring是最广泛使用的Java EE框架之一。我们之前已经介绍了如何使用Spring MVC创建基于Java的Web应用程序。今天我们将学习如何使用Spring MVC创建Spring RESTful Web服务,并使用REST客户端进行测试。最后,我们还将探讨如何使用Spring RestTemplate API调用Spring RESTful Web服务。
Spring REST框架
我们将使用Spring的最新版本4.0.0.RELEASE,并利用Spring Jackson JSON集成来发送JSON响应作为REST调用的响应。本教程使用Spring STS IDE进行开发,以便轻松创建Spring MVC骨架代码,然后进一步实现RESTful架构。在STS中创建一个新的Spring MVC项目后,我们的最终项目结构将如下图所示。我们将逐一查看每个组件。
Spring REST配置的XML文件
我们的pom.xml文件如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Olivia</groupId>
<artifactId>SpringRestExample</artifactId>
<name>SpringRestExample</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>4.0.0.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<jackson.databind-version>2.2.3</jackson.databind-version>
</properties>
<dependencies>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind-version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
STS工具会为我们自动生成pom.xml文件。不过,我已经将Spring框架、AspectJ、SLF4J和Jackson的版本更新到了最新的稳定版本。大部分内容都是通用且自动生成的,需要特别注意的是,我已经在依赖项中添加了Jackson JSON库,因为我们将使用它来实现对象与JSON之间的相互转换。
这是文章《使用JSON、Jackson和客户端程序的Spring RESTful Web服务示例》的第2部分(共5部分)。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 所有Servlet和过滤器共享的根Spring容器定义 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- 创建所有Servlet和过滤器共享的Spring容器 -->
<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>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
这个文件是自动生成的,我在其中没有做任何修改。但是,如果你想改变上下文配置文件和它们的位置,可以在web.xml文件中进行修改。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 根上下文:定义所有其他Web组件可见的共享资源 -->
</beans>
这个文件包含所有网络组件可见的共享资源,我们将要开发一个简单的REST服务,这就是为什么我在这里没有做任何更改的原因。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet上下文:定义此servlet的请求处理基础设施 -->
<!-- 启用Spring MVC @Controller编程模型 -->
<annotation-driven />
<!-- 通过高效提供${webappRoot}/resources目录中的静态资源来处理/resources/**的HTTP GET请求 -->
<resources mapping="/resources/**" location="/resources/" />
<!-- 将@Controller选择的用于渲染的视图解析为/WEB-INF/views目录中的.jsp资源 -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- 配置以在方法处理程序中将JSON作为请求和响应插件 -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- 配置bean以将JSON转换为POJO,反之亦然 -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
<context:component-scan base-package="com.Olivia.spring.controller" />
</beans:beans>
大部分的部分是自动生成的,并包含模板配置。然而需要注意的重要点是支持注解配置的注解驱动元素,并将MappingJackson2HttpMessageConverter插入到RequestMappingHandlerAdapter的messageConverters中,以便Jackson API发挥作用,将JSON转换为Java Beans,反之亦然。通过进行此配置,我们将在请求体中使用JSON,并在响应中接收JSON数据。
Spring REST模型类
让我们编写一个简单的POJO类,用作我们的RESTful网络服务方法的输入和输出。
package com.Olivia.spring.model;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
public class Employee implements Serializable{
private static final long serialVersionUID = -7788619177798333712L;
private int id;
private String name;
private Date createdDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonSerialize(using=DateSerializer.class)
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
唯一需要注意的重点是使用@JsonSerialize注解,通过DateSerializer类实现日期类型在Java和JSON格式之间的双向转换。
春季的Restful Web服务终端点
我们将拥有以下的REST网页服务端点。
序号 | URI | HTTP方法 | 详情 |
---|---|---|---|
1 | /rest/emp/dummy | GET | 健康检查服务,用于在员工数据存储中插入虚拟数据 |
2 | /rest/emp/{id} | GET | 根据ID获取员工对象 |
3 | /rest/emps | GET | 获取数据存储中所有员工的列表 |
4 | /rest/emp/create | POST | 创建员工对象并存储 |
5 | /rest/emp/delete/{id} | PUT | 根据ID从数据存储中删除员工对象 |
我们有一个类,将所有这些URI定义为字符串常量。
package com.Olivia.spring.controller;
public class EmpRestURIConstants {
public static final String DUMMY_EMP = "/rest/emp/dummy";
public static final String GET_EMP = "/rest/emp/{id}";
public static final String GET_ALL_EMP = "/rest/emps";
public static final String CREATE_EMP = "/rest/emp/create";
public static final String DELETE_EMP = "/rest/emp/delete/{id}";
}
Spring的Restful Web服务控制器类
我们的EmployeeController类将发布上述所有的Web服务端点。让我们先看一下这个类的代码,然后我们会详细了解每个方法。
package com.Olivia.spring.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.Olivia.spring.model.Employee;
/**
* 处理员工服务的请求
*/
@Controller
public class EmployeeController {
private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);
//用于存储员工的Map,理想情况下我们应该使用数据库
Map<Integer, Employee> empData = new HashMap<Integer, Employee>();
@RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)
public @ResponseBody Employee getDummyEmployee() {
logger.info("开始获取虚拟员工");
Employee emp = new Employee();
emp.setId(9999);
emp.setName("虚拟员工");
emp.setCreatedDate(new Date());
empData.put(9999, emp);
return emp;
}
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {
logger.info("开始获取员工. ID="+empId);
return empData.get(empId);
}
@RequestMapping(value = EmpRestURIConstants.GET_ALL_EMP, method = RequestMethod.GET)
public @ResponseBody List<Employee> getAllEmployees() {
logger.info("开始获取所有员工.");
List<Employee> emps = new ArrayList<Employee>();
Set<Integer> empIdKeys = empData.keySet();
for(Integer i : empIdKeys){
emps.add(empData.get(i));
}
return emps;
}
@RequestMapping(value = EmpRestURIConstants.CREATE_EMP, method = RequestMethod.POST)
public @ResponseBody Employee createEmployee(@RequestBody Employee emp) {
logger.info("开始创建员工.");
emp.setCreatedDate(new Date());
empData.put(emp.getId(), emp);
return emp;
}
@RequestMapping(value = EmpRestURIConstants.DELETE_EMP, method = RequestMethod.PUT)
public @ResponseBody Employee deleteEmployee(@PathVariable("id") int empId) {
logger.info("开始删除员工.");
Employee emp = empData.get(empId);
empData.remove(empId);
return emp;
}
}
为了简化,我将所有员工的数据都存储在HashMap empData中。@RequestMapping注解用于将请求的URI映射到处理方法上。我们还可以指定客户端应用程序用于调用REST方法的HTTP方法。@ResponseBody注解用于将响应对象映射到响应体中。一旦处理方法返回响应对象,MappingJackson2HttpMessageConverter就会将其转换为JSON响应。@PathVariable注解是从REST URI中提取数据并映射到方法参数的简便方法。@RequestBody注解用于将请求体的JSON数据映射到Employee对象,同样是通过MappingJackson2HttpMessageConverter进行映射。其余代码简单且易懂,我们的应用程序已准备好部署和测试。只需将其导出为WAR文件并将其复制到Servlet容器的Web应用程序目录中。如果您在STS中配置了服务器,只需在服务器上运行它即可进行部署。我正在使用WizTools RestClient来调用REST接口,但您也可以使用Chrome浏览器插件Postman。下面的截图展示了我们的应用程序暴露的REST API的不同调用及其输出。健康检查 – 获取虚拟员工的REST调用 创建员工POST REST调用:确保请求的Content-Type设置为”application/json”,否则会收到HTTP错误代码415。获取员工的REST调用 删除员工的REST调用 获取所有员工的REST调用
Spring的REST客户端程序
使用REST客户端来测试我们的REST Web服务非常好,但大多数情况下,我们需要通过我们的程序调用REST服务。我们可以使用Spring的RestTemplate轻松地调用这些方法。下面是一个使用RestTemplate API调用我们的应用程序REST方法的简单程序。
package com.Olivia.spring;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.web.client.RestTemplate;
import com.Olivia.spring.controller.EmpRestURIConstants;
import com.Olivia.spring.model.Employee;
public class TestSpringRestExample {
public static final String SERVER_URI = "https://localhost:9090/SpringRestExample";
public static void main(String args[]){
testGetDummyEmployee();
System.out.println("*****");
testCreateEmployee();
System.out.println("*****");
testGetEmployee();
System.out.println("*****");
testGetAllEmployee();
}
private static void testGetAllEmployee() {
RestTemplate restTemplate = new RestTemplate();
//we can't get List<Employee> because JSON convertor doesn't know the type of
//object in the list and hence convert it to default JSON object type LinkedHashMap
List<LinkedHashMap> emps = restTemplate.getForObject(SERVER_URI+EmpRestURIConstants.GET_ALL_EMP, List.class);
System.out.println(emps.size());
for(LinkedHashMap map : emps){
System.out.println("ID="+map.get("id")+",Name="+map.get("name")+",CreatedDate="+map.get("createdDate"));;
}
}
private static void testCreateEmployee() {
RestTemplate restTemplate = new RestTemplate();
Employee emp = new Employee();
emp.setId(1);emp.setName("Pankaj Kumar");
Employee response = restTemplate.postForObject(SERVER_URI+EmpRestURIConstants.CREATE_EMP, emp, Employee.class);
printEmpData(response);
}
private static void testGetEmployee() {
RestTemplate restTemplate = new RestTemplate();
Employee emp = restTemplate.getForObject(SERVER_URI+"/rest/emp/1", Employee.class);
printEmpData(emp);
}
private static void testGetDummyEmployee() {
RestTemplate restTemplate = new RestTemplate();
Employee emp = restTemplate.getForObject(SERVER_URI+EmpRestURIConstants.DUMMY_EMP, Employee.class);
printEmpData(emp);
}
public static void printEmpData(Employee emp){
System.out.println("ID="+emp.getId()+",Name="+emp.getName()+",CreatedDate="+emp.getCreatedDate());
}
}
大部分程序很容易理解,然而当调用返回一个集合的REST方法时,我们需要使用LinkedHashMap,因为JSON转换器不知道Employee对象类型,因此将其转换为LinkedHashMap集合。我们可以编写实用方法将LinkedHashMap转换为我们的Java Bean对象。当我们运行上述程序时,控制台会输出以下结果。
ID=9999,Name=Dummy,CreatedDate=Tue Mar 04 21:02:41 PST 2014
*****
ID=1,Name=Pankaj Kumar,CreatedDate=Tue Mar 04 21:02:41 PST 2014
*****
ID=1,Name=Pankaj Kumar,CreatedDate=Tue Mar 04 21:02:41 PST 2014
*****
2
ID=1,Name=Pankaj Kumar,CreatedDate=1393995761654
ID=9999,Name=Dummy,CreatedDate=1393995761381
另一点是,RestTemplate的put方法没有设置响应对象的选项,因为PUT方法应该用于将某些内容存储在服务器上,并且简单的HTTP 200状态码应该足够。
下载Spring Restful Web服务项目
以上就是关于Spring Restful Web应用程序教程的全部内容。请从上面的链接下载示例项目并通过实践来更深入地了解。更新:鉴于有很多人要求提供类似的使用XML的示例,以及支持XML和JSON两种格式的请求和响应,我在Spring REST XML JSON示例中扩展了这个应用程序。我强烈建议您阅读一下,了解Spring框架的美妙之处以及实现这一点的简易性。
您可以从我们的GitHub仓库下载完整的项目。