RestFul風格
Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。
資源:互聯網所有的事物都可以被抽象為資源
資源操作:使用POST、DELETE、PUT、GET,使用不同方法對資源進行操作。
分別對應 添加、 刪除、修改、查詢。
原來的風格
RestFulController:
@Controller
public class RestFulController {
@RequestMapping("/add")
public String test(int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","res = "+ res);
return "admin/test";
}
}
在瀏覽器格式必須為:
http://localhost:8080/add?a=2&b=5
RestFul風格
在Spring MVC中可以使用 @PathVariable 註解,讓方法參數的值對應綁定到一個URI模板變量上。
@Controller
public class RestFulController {
//映射訪問路徑
@RequestMapping("/add/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//Spring MVC會自動實例化一個Model對象用於向視圖中傳值
model.addAttribute("msg", "結果:"+result);
//返回視圖位置
return "test";
}
}
http://localhost:8080/add/5/5
@RequestMap可以加上特定的請求方法,在@RequestMap中添加屬性method = RequestMethod.DELETE(等等):
例如:
@Controller
public class RestFulController {
@RequestMapping(value = "/add/{a}/{b}", method = RequestMethod.GET)
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b ;
model.addAttribute("msg","res = "+ res);
return "admin/test";
}
但是,有下面這些註解更加方便:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
比如:@GetMapping 是一個組合註解,平時使用的會比較多!它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一個快捷方式。其它例子等同。