Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸
基於上一篇《Springboot 整合 Mybatis 的完整 Web 案例》,這邊我們著重在 控制層 講講。講講如何在 Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸。
一、執行 springboot-restful 工程
git clone 下載工程ofollow,noindex" target="_blank">springboot-learning-example ,專案地址見 GitHub -https://github.com/JeffLi1993/springboot-learning-example 。下面開始執行工程步驟(Quick Start):
1.資料庫準備
a.建立資料庫 springbootdb:
CREATE DATABASE springbootdb;
b.建立表 city :(因為我喜歡徒步)
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘城市編號’,
`province_id` int(10) unsigned NOT NULL COMMENT ‘省份編號’,
`city_name` varchar(25) DEFAULT NULL COMMENT ‘城市名稱’,
`description` varchar(25) DEFAULT NULL COMMENT ‘描述’,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
c.插入資料
INSERT city VALUES (1 ,1,’溫嶺市’,’BYSocket 的家在溫嶺。’);
2. springboot-restful 工程專案結構介紹
springboot-restful 工程專案結構如下圖所示:
org.spring.springboot.controller - Controller 層
org.spring.springboot.dao - 資料操作層 DAO
org.spring.springboot.domain - 實體類
org.spring.springboot.service - 業務邏輯層
Application - 應用啟動類
application.properties - 應用配置檔案,應用啟動會自動讀取配置
3.改資料庫配置
開啟 application.properties 檔案, 修改相應的資料來源配置,比如資料來源地址、賬號、密碼等。(如果不是用 SQL/">MySQL,自行新增連線驅動 pom,然後修改驅動名配置。)
4.編譯工程
在專案根目錄 springboot-learning-example,執行 maven 指令:
mvn clean install
5.執行工程
右鍵執行 springboot-restful 工程 Application 應用啟動類的 main 函式。
用 postman 工具可以如下操作,
根據 ID,獲取城市資訊
GET http://127.0.0.1:8080/api/city/1
獲取城市列表
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
二、springboot-restful 工程控制層實現詳解
1.什麼是 REST?
REST 是屬於 WEB 自身的一種架構風格,是在 HTTP 1.1 規範下實現的。Representational State Transfer 全稱翻譯為表現層狀態轉化。Resource:資源。比如 newsfeed;Representational:表現形式,比如用JSON,富文字等;State Transfer:狀態變化。通過HTTP 動作實現。
理解 REST ,要明白五個關鍵要素:
資源(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-style
2.Spring 對 REST 支援實現
CityRestController.java 城市 Controller 實現 Restful HTTP 服務
public class CityRestController { @Autowired private CityService cityService; @RequestMapping(value = "/api/city/{id}", method = RequestMethod.GET) public City findOneCity(@PathVariable("id") Long id) { return cityService.findCityById(id); } @RequestMapping(value = "/api/city", method = RequestMethod.GET) public List<City> findAllCity() { return cityService.findAllCity(); } @RequestMapping(value = "/api/city", method = RequestMethod.POST) public void createCity(@RequestBody City city) { cityService.saveCity(city); } @RequestMapping(value = "/api/city", method = RequestMethod.PUT) public void modifyCity(@RequestBody City city) { cityService.updateCity(city); } @RequestMapping(value = "/api/city/{id}", method = RequestMethod.DELETE) public void modifyCity(@PathVariable("id") Long id) { cityService.deleteCity(id); } }
具體 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/html
produces - 指定返回的內容型別
@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協議 》
三、小結
Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸,適用於前後端分離。這只是個小demo,沒有加入bean validation這種校驗。還有各種業務場景。