獲取城市列表GET http://127.0.0.1:8080/api/city
新增城市信息POST http://127.0.0.1:8080/api/city
更新城市信息PUT http://127.0.0.1:8080/api/city
刪除城市信息DELETE http://127.0.0.1:8080/api/city/2
資源(Resource)資源的表述(Representation)狀態轉移(State Transfer)統一接口(Uniform Interface)超文本驅動(Hypertext Driven)6 個主要特性:面向資源(Resource Oriented)可尋址(Addressability)連通性(Connectedness)無狀態(Statelessness)統一接口(Uniform Interface)超文本驅動(Hypertext Driven)具體這里就不一一展開,詳見 http://www.infoq.com/cn/articles/understanding-restful-style2.Spring 對 REST 支持實現CityRestController.java 城市 Controller 實現 Restful HTTP 服務具體 Service 、dao 層實現看代碼GitHub https://github.com/JeffLi1993/springboot-learning-example/tree/master/springboot-restful代碼詳解:@RequestMapping 處理請求地址映射。method – 指定請求的方法類型:POST/GET/DELETE/PUT 等value – 指定實際的請求地址consumes – 指定處理請求的提交內容類型,例如 Content-Type 頭部設置application/json, text/htmlproduces – 指定返回的內容類型@PathVariable URL 映射時,用于綁定請求參數到方法參數@RequestBody 這里注解用于讀取請求體 boy 的數據,通過 HttpMessageConverter 解析綁定到對象中3.HTTP 知識補充GET 請求獲取Request-URI所標識的資源POST 在Request-URI所標識的資源后附加新的數據HEAD 請求獲取由Request-URI所標識的資源的響應消息報頭PUT 請求服務器存儲一個資源,并用Request-URI作為其標識DELETE 請求服務器刪除Request-URI所標識的資源TRACE 請求服務器回送收到的請求信息,主要用于測試或診斷CONNECT 保留將來使用OPTIONS 請求查詢服務器的性能,或者查詢與資源相關的選項和需求詳情請看《JavaEE 要懂的小事:一、圖解Http協議》
123456789101112131415161718192021222324252627282930 publicclassCityRestController {@AutowiredprivateCityService cityService;@RequestMapping(value ="/api/city/{id}", method = RequestMethod.GET)publicCity findOneCity(@PathVariable("id") Long id) {returncityService.findCityById(id);}@RequestMapping(value ="/api/city", method = RequestMethod.GET)publicList<City> findAllCity() {returncityService.findAllCity();}@RequestMapping(value ="/api/city", method = RequestMethod.POST)publicvoidcreateCity(@RequestBodyCity city) {cityService.saveCity(city);}@RequestMapping(value ="/api/city", method = RequestMethod.PUT)publicvoidmodifyCity(@RequestBodyCity city) {cityService.updateCity(city);}@RequestMapping(value ="/api/city/{id}", method = RequestMethod.DELETE)publicvoidmodifyCity(@PathVariable("id") Long id) {cityService.deleteCity(id);}}三、小結
Springboot 實現 Restful 服務,基于 HTTP / JSON 傳輸,適用于前后端分離。這只是個小demo,沒有加入bean validation這種校驗。還有各種業務場景。推薦:《 Springboot 整合 Mybatis 的完整 Web 案例》歡迎掃一掃我的公眾號關注 — 及時得到博客訂閱哦!— http://www.bysocket.com/ —— https://github.com/JeffLi1993 —
新聞熱點
疑難解答