pyqb

导航

 

RESTful API设计需求如下:

 

 

User.java

 1 package com.springboot.test;
 2 
 3 public class User {
 4     private Long id;
 5     private String name;
 6     private Integer age;
 7 
 8     public Long getId() {
 9         return id;
10     }
11 
12     public void setId(Long id) {
13         this.id = id;
14     }
15 
16     public String getName() {
17         return name;
18     }
19 
20     public void setName(String name) {
21         this.name = name;
22     }
23 
24     public Integer getAge() {
25         return age;
26     }
27 
28     public void setAge(Integer age) {
29         this.age = age;
30     }
31 }

 

UserController.java

 1 package com.springboot.test;
 2 
 3 import org.springframework.web.bind.annotation.*;
 4 import java.util.*;
 5 
 6 @RestController
 7 @RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下
 8 public class UserController {
 9 
10     // 创建线程安全的Map 
11     static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
12 
13     @RequestMapping(value="", method= RequestMethod.GET)
14     public List<User> getUserList() {
15         // 处理"/users/"的GET请求,用来获取用户列表 
16         // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 
17         List<User> r = new ArrayList<User>(users.values());
18         return r;
19     }
20 
21     @RequestMapping(value="/", method=RequestMethod.POST)
22     public String postUser(@ModelAttribute User user) {
23         // 处理"/users/"的POST请求,用来创建User 
24         // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
25         users.put(user.getId(), user);
26         return "success";
27     }
28 
29     @RequestMapping(value="/{id}", method=RequestMethod.GET)
30     public User getUser(@PathVariable Long id) {
31         // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 
32         // url中的id可通过@PathVariable绑定到函数的参数中 
33         return users.get(id);
34     }
35 
36     @RequestMapping(value="/{id}", method=RequestMethod.POST)
37     public String putUser(@PathVariable Long id, @ModelAttribute User user) {
38         // 处理"/users/{id}"的PUT请求,用来更新User信息 
39         User u = users.get(id);
40         u.setName(user.getName());
41         u.setAge(user.getAge());
42         users.put(id, u);
43         return "success";
44     }
45 
46     @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
47     public String deleteUser(@PathVariable Long id) {
48         // 处理"/users/{id}"的DELETE请求,用来删除User 
49         users.remove(id);
50         return "success";
51     }
52 }

 

运行,使用postman测试

先post两个数据,发送成功返回success。

 

 

 发get请求

 

 get请求某个id的数据

 

post修改数据

 

get数据查看是否修改好数据

 

删除数据

 

get查看数据,发现id为2的数据已删除

 

posted on 2017-11-28 18:05  没有音乐就退化耳朵  阅读(340)  评论(0编辑  收藏  举报