rest风格是一个看起来极其简洁的方式
传统风格:
当我们在浏览器上访问一些资源时,可以看到有些网页的url为
http: // localhost / students / selectById?id=1 (该地址表示查找id为1的students对象)
http: // localhost / students / saveStudent (该地址表示保存students信息)
REST风格:
这两句url与上面两句功能是一样的
http: // localhosts / student / 1
http: // localhosts / student
通过这两种风格的对比,我们可以看到REST风格的一部分优点:
可以隐藏资源的访问行为,这样就无法通过地址得知对资源进行了哪种操作。
可以明显的看到其书写简化了,不仅书写简化了,在开发时代码也可以简化。
常用的四种请求方式
- GET (常用于查询)
- POST(常用于保存)
- PUT(常用于更新修改)
- DELETE(常用于删除)
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;import java.util.ArrayList;
import java.util.List;@SpringBootApplication
@RestController
public class DemoApplication {private List<String> fruits = new ArrayList<>();
@GetMapping("/fruits")
public List<String> getFruits() {
return fruits;
}@PostMapping("/fruits")
public String addFruit(@RequestBody String fruit) {
fruits.add(fruit);
return "Added " + fruit;
}@DeleteMapping("/fruits")
public String deleteFruits() {
fruits.clear();
return "All fruits deleted";
}@DeleteMapping("/fruits/{index}")
public String deleteFruit(@PathVariable int index) {
if (index < 0 || index >= fruits.size()) {
return "Invalid index";
}
fruits.remove(index);
return "Fruit at index " + index + " deleted";
}public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}}
前端请求
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>RESTful API Example</title>
</head>
<body>
<h1>RESTful API Example</h1>
<h3>Current Fruits:</h3>
<ul id="fruits"></ul>
<input type="text" id="new-fruit">
<button οnclick="addFruit()">Add Fruit</button>
<button οnclick="deleteFruits()">Delete All Fruits</button>
<br><br>
<label>Delete fruit at index:</label>
<input type="number" id="delete-index">
<button οnclick="deleteFruit()">Delete Fruit</button><script>
function updateFruits() {
fetch("/fruits").then(response => {
return response.json();
}).then(data => {
let list = document.getElementById("fruits");
list.innerHTML = "";
data.forEach(fruit => {
let item = document.createElement("li");
item.appendChild(document.createTextNode(fruit));
list.appendChild(item);
});
});
}function addFruit() {
let fruit = document.getElementById("new-fruit").value;
fetch("/fruits", {
method: "POST",
body: fruit
}).then(response => {
return response.text();
}).then(data => {
alert(data);
updateFruits();
});
}function deleteFruits() {
fetch("/fruits", {
method: "DELETE"
}).then(response => {
return response.text();
}).then(data => {
alert(data);
updateFruits();
});
}function deleteFruit() {
let index = document.getElementById("delete-index").value;
fetch("/fruits/" + index, {
method: "DELETE"
}).then(response => {
return response.text();
}).then(data => {
alert(data);
updateFruits();
});
}updateFruits();
</script>
</body>
</html>