REST(Representational State Transfer),表现形式状态转换,它是一种软件架构风格
当我们想表示一个网络资源的时候,可以使用两种方式:
-
传统风格资源描述形式
-
http://localhost/user/getById?id=1
查询id为1的用户信息 -
http://localhost/user/saveUser
保存用户信息
-
-
REST风格描述形式
http://localhost/user/1
http://localhost/user
传统方式一般是一个请求url对应一种操作,这样做不仅麻烦,也不安全,因为会程序的人读取了你的请求url地址,就大概知道该url实现的是一个什么样的操作。
查看REST风格的描述,你会发现请求地址变的简单了,并且光看请求URL并不是很能猜出来该URL的具体功能。
Rest的优点有:
- 隐藏资源的访问行为,无法通过地址得知对资源是何种操作
- 书写简化
存在的问题:一个相同的url地址如何区分具体的操作,是新增、修改还是查询?
解决方案:使用不同的行为动作区分对资源进行了何种操作
http://localhost/users
查询全部用户信息 GET(查询)
http://localhost/users/1
查询指定用户信息 GET(查询)
http://localhost/users
添加用户信息 POST(新增/保存)
http://localhost/users
修改用户信息 PUT(修改/更新)
http://localhost/users/1
删除用户信息 DELETE(删除)
常用的请求操作分为4种,分别是GET、POST、PUT、DELETE。
- 发送GET请求用来进行查询操作
- 发送POST请求用来新增
- 发送PUT请求用来做修改
- 发送DELETE请求用来做修改
之前统一使用@RequestMapping注解时的Controller代码
1 @Controller
2 public class UserController {
3 @RequestMapping("/save")
4 @ResponseBody
5 public String save(@RequestBody User user) {
6 System.out.println("user save..."+user);
7 return "{'module':'user save'}";
8 }
9
10 @RequestMapping("/delete")
11 @ResponseBody
12 public String delete(Integer id) {
13 System.out.println("user delete..." + id);
14 return "{'module':'user delete'}";
15 }
16
17 @RequestMapping("/update")
18 @ResponseBody
19 public String update(@RequestBody User user) {
20 System.out.println("user update..." + user);
21 return "{'module':'user update'}";
22 }
23
24 @RequestMapping("/getById")
25 @ResponseBody
26 public String getById(Integer id) {
27 System.out.println("user getById..." + id);
28 return "{'module':'user getById'}";
29 }
30
31 @RequestMapping("/findAll")
32 @ResponseBody
33 public String getAll() {
34 System.out.println("user getAll...");
35 return "{'module':'user getAll'}";
36 }
37 }
修改后,使用@GetMapping、@PostMapping、@DeleteMapping、@PutMapping替代
1 @RestController //使用@RestController注解替换@Controller与@ResponseBody注解,简化书写
2 @RequestMapping("/users")
3 public class UserController {
4 @PostMapping
5 public String save(@RequestBody User user) {
6 System.out.println("user save..."+user);
7 return "{'module':'user save'}";
8 }
9
10 //使用@DeleteMapping简化DELETE请求方法对应的映射配置
11 @DeleteMapping("/{id}")
12 public String delete(Integer id) {
13 System.out.println("user delete..." + id);
14 return "{'module':'user delete'}";
15 }
16
17 //使用@PutMapping简化Put请求方法对应的映射配置
18 @PutMapping
19 public String update(@RequestBody User user) {
20 System.out.println("user update..." + user);
21 return "{'module':'user update'}";
22 }
23
24 //使用@GetMapping简化GET请求方法对应的映射配置
25 @GetMapping("/{id}")
26 public String getById(Integer id) {
27 System.out.println("user getById..." + id);
28 return "{'module':'user getById'}";
29 }
30
31 //使用@GetMapping简化GET请求方法对应的映射配置
32 @GetMapping
33 public String getAll() {
34 System.out.println("user getAll...");
35 return "{'module':'user getAll'}";
36 }
37 }