概念
Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。
功能
資源:互聯網所有的事物都可以被抽象爲資源
資源操作:使用POST、DELETE、PUT、GET,使用不同方法 對資源進行操作。
分別對應 添加、 刪除、修改、查詢。
我們先看一下瀏覽器中一些百度百科中的地址這就是RestFul風格.
這種風格不是與生俱來的,也需要演變.
下面說說原始風格的.
代碼:
package com.qiu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestfulContraller {
//http://localhost:8080/add?a=1&b=2 之前的寫法
@RequestMapping("/add")
public String test(int a, int b , Model model){
int res = a+b;
model.addAttribute("msg","結果爲"+res);
return "test";
}
}
在瀏覽器中,如果直接輸入/add則會出現500錯誤
這個時候我們要傳入參數
這樣結果纔出來了,但是這種寫法太過於繁瑣,所以就有了RestFul風格
代碼:
package com.qiu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestfulContraller {
//http://localhost:8080/add?a=1&b=2 之前的寫法
//RestFul :http://localhost:8080/add/a/b
@RequestMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b , Model model){
int res = a+b;
model.addAttribute("msg","結果爲"+res);
return "test";
}
}
這樣就減少了繁瑣的輸入.