RESTful Web Services
REST即REpresentational State Transfer,REST 是一种基于网络的软件架构约束,使用HTTP协议进行数据交换。基于REST架构的Web Services叫做RESTful Web Services。
REST的主要原则如下:
网络上的所有事物都可被抽象为资源(Resource)。
每个资源都有一个唯一的资源标识符(Resource Identifier)。
同一资源具有多种表现形式。
使用标准方法操作资源。
通过缓存来提高性能。
对资源的各种操作不会改变资源标识符。
所有的操作都是无状态的(Stateless)。
REST 架构是针对传统 Web 应用提出的一种改进,是一种新型的分布式软件设计架构。对于异构系统如何整合的问题,目前主流做法都集中在使用 SOAP、WSDL 和 WS-* 规范的 Web Services。而 REST 架构实际上也是解决异构系统整合问题的一种新思路。
现在的云服务提供支持REST的API,如OpenStack.
在这种原则下,网络上的各种资源可以有统一的命名规则,URI,人们可以通过URI来判断自己访问了什么资源,而不是只有开发人员能看懂某个方法,如user!list?page=1&pageSize=10
以下HTTP方法在RESTful Web Services里非常常用,至于具体的定义,还需看各个框架自己的设定,但大体一致。
Get方法, Provides a read only access to a resource
/UserService/users 查询user的list,read only
/UserService/users/1,查询id为1的user,read onlyPut方法, Used to create a new resource
/UserService/users/2,增加一位user,id=2,idempotent幂等性
Delete, Used to remove a resource
/UserService/users/1,删除id为1的user,idempotent幂等性
Post, Used to update a existing resource or create a new resource
/UserService/users/2,更新id为2的user
OPTIONS, Used to get the supported operations on a resource
/UserService/users, 列出web services支持定义的某个list,Read Only
Struts2 REST实例
Struts2在自己的学习和做项目过程中都用过,下面以框架为例,开发一个REST架构的页面。
步骤一:建立Struts2项目,除了Struts2最基本的jar包,还需rest,convention,json-lib,xstream四个jar包
步骤二:配置Struts.xml,
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<!-- 只想用REST 就配置这个-->
<!-- <constant name="struts.mapper.class" value="rest" /> -->
<!-- REST和非REST风格一起用, 就配置这个-->
<!-- <constant name="struts.action.extension" value="xhtml,,xml,json,action"/> -->
<!-- 以上可以不设,不论哪种,都要设定以下项目 -->
<!-- XXXAction类后缀,可以是Controller,那么所有控制器后缀都设为Controller-->
<constant name="struts.convention.action.suffix" value="Action" />
<constant name="struts.convention.action.mapAllMatches" value="true" />
<constant name="struts.convention.default.parent.package" value="rest-default" />
<!-- Action类所在包名 -->
<constant name="struts.convention.package.locators" value="action" />
</struts>
步骤三:编写User.java,UserDao.java,UserService.java,注意struts2 rest插件提供的默认REST方法
User.java
package com.rest.bean;
public class User {
private Integer id;
private String userName;
private Integer age;
public User() {
}
public User(Integer id, String userName, Integer age) {
super();
this.id = id;
this.userName = userName;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
UserDao.java<