使用 Spring 3 构建基于 HTTP 的RESTful Web Services

本文不讲述 RESTful Web Services 的概念和理论,你需要了解什么是 RESTful Web Services。

本文不讲述 Spring Framework 的使用和技巧,你需要熟悉 Spring Framework 和 Spring MVC。

本文内容主要是简单说明使用 Spring 3 来构建一个简易的 RESTful Web Service 相关内容。

Spring 自版本3开始增加了对 RESTful Web Services 开发的支持,且 REST 已被无缝整合到了 Spring 的 MVC 框架中,因此在 Spring 中创建 RESTful Web Services 是十分容易的。这主要体现在:

  • 通过 @RequestMapping, @PathVariable, @RequestBody, @ResponseBody 等注解(Annotation)可以简单的创建资源标识和URI映射
  • 丰富的数据载体支持,比如 XML、JSON
  • 完全采用 Spring MVC 模型进行开发,使用 Spring 开发的应用可无缝过渡到 REST


下面通过一个例子来说明使用 Spring 3 创建一个 RESTful Web Service 需要的操作。

对于本例的几点说明:

  1. 通信协议为 HTTP 协议;
  2. 参数类型为 JSON 格式;
  3. 例子中的代码均采用省略的写法,只写出需要注意的部分;

代码依赖

  • spring-webmvc
  • jackson-core-asl
  • jackson-mapper-asl

如果使用 Maven 的话可以参考如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>


Java 实现

本例中我们假设只有一个 Entity 对象 Customer,实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
package demo.rest.model;
public class Customer {
private long id;
private String name;
private String mobile;
private String address;
private String email;
// omit implementation of Getters and Setters below
// ......
}


同时,针对 Customer 的持久化操作实现 CustomerRepository 大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package demo.rest.repo;
public class CustomerRepository {
public Customer query(long id) {
// omitted
}
public List<Customer> queryAll() {
// omitted
}
public void add(Customer customer) {
// omitted
}
public void update(Customer customer) {
// omitted
}
public void remove(long id) {
// omitted
}
}



阅读全文