Java框架spring Boot學習筆記(九):一個簡單的RESTful API

RESTful API設計需求以下:java

 

 

User.javaweb

 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.javaspring

 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。springboot

 

 

 發get請求app

 

 get請求某個id的數據函數

 

post修改數據post

 

get數據查看是否修改好數據測試

 

刪除數據this

 

get查看數據,發現id爲2的數據已刪除

相關文章
相關標籤/搜索