面試題:你平時是怎麼設計接口的?
基於RESTful風格設計接口,RESTful風格主要體現在資源上,每一個資源都有唯一的URL標識。對於不同的行爲,使用對應的http-method操作。對於相同的URL,如果http-method不同,那麼獲取的資源也就不同。
RESTful風格中,不允許出現動詞,應該使用資源的名詞。結構很清晰明瞭,並且安全性更高(比如以前刪除用戶的URL是這樣寫的:http://localhost/xxx/deleteUserById/id,別人一看到這個URL就知道你是要刪除某個用戶了,然後就可以推測出內部實現來進行非法操作;而在RESTful中URL是這樣寫的:http://localhost/xxx/user/id,看到這個URL就蒙圈了,因爲從這個URL中我們根本就看不出是刪除、修改還是查詢操作)
RESTful(REpresentational State Transfer)"資源"
表現性狀態轉移。在RESTful風格中,一切都被認爲是資源,每個資源都有對應的URI標識。處理資源時使用GET、POST、PUT、DELETE等http方法來實現新增、查詢、修改、刪除的操作。
RESTful是一種設計風格而不是標準(並不是所有API都要求這樣設計),只是提供了一組設計原則和約束條件。
RESTful規則:
-
每個資源都有唯一的URL標識
-
對於不同的行爲,使用對應的http-method
-
URL中不允許出現動詞,需使用名詞(因爲RESTful中URL代表的是一個資源,雖然使用動詞不會出錯,但不符合RESTful的設計規範)
-
RESTful風格中,把所有東西都看成是資源,一張圖片是資源、一段音頻是資源
-
只返回數據(JSON / XML),不包含任何展現(典型的前後端分離,適合各種客戶端開發(PC、Android、iPhone))
常用http-method:
-
GET 查詢
-
POST 新增
-
PUT 更新
-
DELETE 刪除
請求方式 | 標識 | 意圖 |
---|---|---|
GET | http://caidong4356.top/xxx/users | 查詢所有用戶 |
POST | http://caidong4356.top/xxx/users | 新增一個用戶 |
PUT | http://caidong4356.top/xxx/users | 修改一個用戶 |
DELETE | http://caidong4356.top/xxx/users/1 | 刪除用戶1 |
GET | http://caidong4356.top/xxx/users/1 | 查詢用戶1 |
GET | http://caidong4356.top/xxx/users/1/orders | 查詢用戶1的所有訂單 |
GET | http://caidong4356.top/xxx/users/1/order | 給用戶1新增一個訂單 |
案例
public class User {
private Integer userId;
private String username;
private String password;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date birthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/users")
public List<User> getUsers(){
List list = new ArrayList();
User u1 = new User();
u1.setUserId(1);
u1.setUsername("Jack");
u1.setBirthday(new Date());
list.add(u1);
User u2 = new User();
u2.setUserId(2);
u2.setUsername("Lily");
u2.setBirthday(new Date());
list.add(u2);
return list;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable("id")Integer userId){
User u = new User();
if(userId == 1){
u.setUserId(1);
u.setUsername("Jack");
u.setBirthday(new Date());
}else {
u.setUserId(2);
u.setUsername("Lily");
u.setBirthday(new Date());
}
return u;
}
@GetMapping("/name/{name}")
public User getUserByName(@PathVariable("name")String username){
User u = new User();
if(username.equals("Jack")){
u.setUserId(1);
u.setUsername("Jack");
u.setBirthday(new Date());
}else if(username.equals("Lily")){
u.setUserId(2);
u.setUsername("Lily");
u.setBirthday(new Date());
}
return u;
}
@PostMapping("")
public String addUser(){
return "{\"message\" : \"數據添加成功\"}";
}
@PutMapping("/{id}")
public Map<String,Object> updateUserById(@PathVariable("id")Integer userId) {
Map map = new HashMap();
map.put("message","數據修改成功");
map.put("userId", userId);
return map;
}
@DeleteMapping("/{id}")
public Map<String,Object> deleteUserById(@PathVariable("id")Integer userId) {
Map map = new HashMap();
map.put("message","數據刪除成功");
map.put("userId", userId);
return map;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>RESTful風格</title>
<script src="../js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#getBtn").click(function () {
$.ajax({
url: "/user/users",
type: "get",
dataType: "json",
success: function (data) {
var temp = "";
$("tbody").empty();
if(data.length > 0){
$("table").show();
data.map(function (item, index) {
temp +=
"<tr>" +
"<td>" + item.userId + "</td>" +
"<td>" + item.username + "</td>" +
"<td>" + item.birthday + "</td>" +
"<tr>";
});
$("tbody").append(temp);
}
}
})
});
$("#getByIdBtn").click(function () {
$.ajax({
url: "/user/2",
type: "get",
dataType: "json",
success: function (data) {
$("tbody").empty();
$("table").show();
var temp = "";
temp +=
"<tr>" +
"<td>" + data.userId + "</td>" +
"<td>" + data.username + "</td>" +
"<td>" + data.birthday + "</td>" +
"<tr>";
$("tbody").append(temp);
}
})
});
$("#getByNameBtn").click(function () {
$.ajax({
url: "/user/name/Jack",
type: "get",
dataType: "json",
success: function (data) {
$("tbody").empty();
$("table").show();
var temp = "";
temp +=
"<tr>" +
"<td>" + data.userId + "</td>" +
"<td>" + data.username + "</td>" +
"<td>" + data.birthday + "</td>" +
"<tr>";
$("tbody").append(temp);
}
})
});
$("#postBtn").click(function () {
$.ajax({
url: "/user",
type: "post",
dataType: "json",
success: function (data) {
$("#message").text(data.message);
}
})
});
$("#putBtn").click(function () {
$.ajax({
url: "/user/1",
type: "put",
dataType: "json",
success: function (data) {
$("#message").text(data.userId +":"+ data.message);
}
})
});
$("#deleteBtn").click(function () {
$.ajax({
url: "/user/2",
type: "delete",
dataType: "json",
success: function (data) {
$("#message").text(data.userId +":"+ data.message);
}
})
});
})
</script>
</head>
<body>
<div>
<input type="button" id="postBtn" value="postBtn">
<input type="button" id="putBtn" value="putBtn">
<input type="button" id="deleteBtn" value="deleteBtn">
</div>
<div id="message"></div>
<br>
<div>
<input type="button" id="getByIdBtn" value="getByIdBtn">
<input type="button" id="getByNameBtn" value="getByNameBtn">
<input type="button" id="getBtn" value="getBtn">
<table border="1" cellspacing="0" bordercolor="gray" style="display: none">
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>生日</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
URL = 域名 + URI
Spring4特性註解: @RestController = @Controller + @ResponseBody
標註該註解的Controller類,其方法返回值爲JSON類型
路徑變量:放在URI中的變量被稱爲路徑變量