RESTful架構:是一種設計的風格,並不是標准,只是提供了一組設計原則和約束條件,也是目前比較流行的一種互聯網軟件架構。它結構清晰、符合標准、易於理解、擴展方便,所以正得到越來越多網站的采用。
關於RESTful架構給你一個鏈接講的挺好的:http://www.ruanyifeng.com/blog/2011/09/restful
這里我結合springMVC講解一下RESTful在springMVC中的使用,在講之前先來看看RESTful提倡哪些做法:
- 他會對url進行規范:
a) 非REST風格的url:localhost:8080/springmvc?name=小白&password=123;
b) REST風格的url:localhost:8080/springmvc/小白/123;
分析:
-
- 直觀上看是不是比較簡潔
- 看不懂:隱藏了參數名稱,安全性,防止被攻擊
- 所有的url都可以當成是資源
- 對http的方法進行規范
a)不管是刪除,添加,更新….使用的url都是一致,那么如果需要刪除,就把http的方法設置刪除
b) 控制器:通過判斷http的方法來執行操作(增刪改查)
目前這種做法還沒有被廣泛采用
3.對contentType也進行規范
a) 就是在請求是指定contentType的類型(json交互中就有體現)
4.接下來看看springMVC中怎么實現RESTful風格
首先:你在請求路徑上@RequestMapping(value = "/hello_rest/{name}/{password}")需要用{}來動態匹配參數
其次:方法的形參上要@PathVariable("name")來匹配上面的參數,這里@PathVariable中的字符串必須和你{}中的名字一致
訪問路徑:localhost:8080/工程名/hello_rest/xx/xx(其中xx就是你隨便填寫的內容,它會匹配到后台的name和password的值)
比如:
你輸入的路徑是:localhost:8080/工程名/hello_rest/小白/admin
后台會匹配到:name="小白",password="admin"
/** * 1.路徑的變化:/hello_rest/{name}/{password}其中{}相當於可以的參數 * 2.參數的寫法:需要利用@PathVariable("name")來匹配上面的參數 * 3.至於@PathVariable后面跟的形參你就可以隨便命名了 * @param username * @param password * @return */ @RequestMapping(value = "/hello_rest/{name}/{password}") public String hello_rest(@PathVariable("name") String username, @PathVariable("password") String password) { if("admin".equals(username)&"123".equals(password)){ System.out.println("登錄成功"); return "hello"; } return "hello"; }
這種寫法和第一種類似,只不過是把{}動態匹配參數的放到前面去了,其原理是一樣的,不多說,直接看看這個訪問路徑的寫法就好
訪問路徑:localhost:8080/工程名/xx/xx/hello_rest
只是把參數由后面放到前面去了而已。
/** * 1.路徑的變化:/{name}/{password}/hello_rest其中{}相當於可以的參數 * 2.參數的寫法:需要利用@PathVariable("name")來匹配上面的參數 * 3.至於@PathVariable后面跟的形參你就可以隨便命名了 * @param username * @param password * @return */ @RequestMapping(value = "/{name}/{password}/hello_rest") public String hello_rest2(@PathVariable("name") String username, @PathVariable("password") String password) { if("admin".equals(username)&"123".equals(password)){ System.out.println("登錄成功"); return "hello"; } return "hello"; }