Java RESTful
REST 服务的核心是对外公布的资源 API 。定义资源通常包括资源实体及其表述的设计、资源路径的定义,最后是使用 jax-rs 2.0 对定义好的资源 API 进行编码实现。
- 实践一个 REST 应用,需要考虑两点:
如何定义一个资源,包括以什么方式发布一个请求,它的输入输出是什么;
如何部署一个 java restful web service application,以匹配既有的 REST 服务类型。
资源地址 URL 规则:HTTP 服务器地址/REST 服务名称/myresource/
-
设备实体类、资源类(公布设备的 rest api)、逻辑分层类(API 层、Service 层、数据访问层)
// 实体类 @XmlRootElement(name="device") public class Device { private String deviceIp; private int deviceStatus; public Device() { } public Device(String deviceIp) { super(); this.deviceIp = deviceIp; } @XmlAttribute(name="ip") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } @XmlAttribute(name="status") public int getDeviceStatus() { return deviceStatus; } public void setDeviceStatus(int deviceStatus) { this.deviceStatus = deviceStatus; } } // 资源类 @Path("device") public class DeviceResource { private final DeviceDao deviceDao; public DeviceResource() { deviceDao = new DeviceDao(); } @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Device get(@QueryParam("ip") final String deviceIp) { Device result = null; if(deviceIp != null ) { result = deviceDao.getDevice(deviceIp); } return result; } @PUT @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Device put(final Device device) { Device result = null; if(device != null ) { result = deviceDao.updateDevice(device); } return result; } }
-
资源路径
有了实体类,根据业务为其定义资源路径,以对外提供方 REST 服务。
eg.图书资源路径列表
resource path | rest interface desc | http method | input | output |
---|---|---|---|---|
/books | 获取全部图书资源 | GET | Books | |
/books/{bookId:[0-9]*} | 通过主键获取指定图书资源 | GET | bookId | Book |
/books/book?id=... | 通过主键获取指定图书资源 | GET | id | Book |
/books | 新增图书资源 | POST | Book | Book |
/books/{bookId:[0-9]*} | 通过主键更新指定图书资源 | PUT | bookId Book | Book |
/books/{bookId:[0-9]*} | 通过主键删除指定图书资源 | DELETE | bookId | 删除结果字符串 |
在资源路径的绑定定义中,可以使用正则表达式。[修改使用 PUT 方法,新增使用 POST 方法]
定义资源路径就是设计 REST 接口的过程,一方面需要对业务有深刻的理解,另一方面需要对 REST 风格有真知灼见。