1. 程式人生 > 實用技巧 >RestFul風格

RestFul風格

概念:Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格 設計的軟體可以更簡潔,更有層次,更易於實現快取等機制。

功能資源:網際網路所有的事物都可以被抽象為資源

資源操作:使用POST、DELETE、PUT、GET,使用 不同方法對資源進行操作。 分別對應 新增、 刪除、修改、查詢。

傳統方式操作資源 :通過不同的引數來實現不同的效果!方法單一,post 和 get

http://127.0.0.1/item/queryItem.action?id=1 查詢,GET 
http://127.0.0.1/item/saveItem.action 新 增,POST  
http://127.0.0.1/item/updateItem.action 更新,POST 
http://127.0.0.1/item/deleteItem.acti on?id=1 刪除,GET或POST

使用RESTful操作資源 : 可以通過不同的請求方式來實現不同的效果!如下:請求地址一樣,但是功能 可以不同!

http://127.0.0.1/item/1 查詢,GET 
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 刪除,DELETE

程式碼測試

@Controller
public class RestFulController {

    //原來請求url:http://localhost:8080/springmvc_04_controller_war_exploded/hello?a=1&b=9

    
//restFul:http://localhost:8080/springmvc_04_controller_war_exploded/hello/1/9 //@RequestMapping(value = "/hello/{a}/{b}",method = RequestMethod.GET) @GetMapping("/hello/{a}/{b}") public String Test(@PathVariable int a,@PathVariable int b, Model model){ int result=a+b; model.addAttribute(
"msg","1、結果為"+result); return "test"; } //@RequestMapping(value = "/hello/{a}/{b}",method = RequestMethod.POST) @PostMapping("/hello/{a}/{b}") public String Test2(@PathVariable int a,@PathVariable int b, Model model){ int result=a+b; model.addAttribute("msg","2、結果為"+result); return "test"; } }