REST

一、REST 是什么?

REST(Representational State Transfer) 是一种基于 HTTP 协议的 软件架构风格,由 Roy Fielding 在 2000 年提出。它强调以 资源(Resource) 为核心,通过统一的接口(如 HTTP 方法)对资源进行操作,适用于构建分布式、可扩展的 Web 服务。

传统风格资源描述形式

1
2
http://localhost/user/getById?id=1
http://localhost/user/saveUser

REST风格描述形式:

1
2
http://localhost/user/1
http://localhost/user

我们可以看到,这种风格的描述形式隐藏了资源的访问行为,无法通过地址得知资源是何种操作

那要怎么区分呢?

按照REST风格访问资源时使用行为动作区分对资源进行了何种操作

1
2
3
4
5
http://localhost/users	查询全部用户信息GET (查询)
http://1ocalhost/users/1 直询指定用户信息GET (查询)
http://1ocalhost/users 添加用户信息POST (新增/保存)
http://1ocalhost/users 修改用户信息PUT(修改/更新)
http://localhost/users/1 删除用户信息DELETE (删除)

根描REST风格対路源进行访問称为RESTful

下面是具体案例:

修改前:

1
2
3
4
5
6
7
@RequestMapping("/delete" )
@ResponseBody
public String delete(Integer id){
System.out.println("user delete..." + id);
return "{'module':'user delete'}";
}

修改后:

1
2
3
4
5
6
7
@RequestMapping(value ="/users",method = RequestMethod.DELETE)
@ResponseBody
public String delete(Integer id){
System.out.println("user delete..."+ id);
return "('module':'user delete'}";
}