Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸
“怎樣的人生才是沒有遺憾的人生?我的體會是:(1)擁有健康;(2)創造“難忘時刻”;(3)盡力做好自己,不必改變世界;(4)活在當下。” – 《向死而生》李開複
基於上一篇《Springboot 整合 Mybatis 的完整 Web 案例》,這邊我們著重在 控製層 講講。講講如何在 Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸。
一、運行 springboot-restful 工程
git clone 下載工程 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 文件, 修改相應的數據源配置,比如數據源地址、賬號、密碼等。(如果不是用 MySQL,自行添加連接驅動 pom,然後修改驅動名配置。)
4.編譯工程
在項目根目錄 springboot-learning-example,運行 maven 指令:
mvn clean install
5.運行工程
右鍵運行 springboot-restful 工程 Application 應用啟動類的 main 函數。
用 postman 工具可以如下操作,
根據 ID,獲取城市信息
GET https://127.0.0.1:8080/api/city/1
獲取城市列表
GET https://127.0.0.1:8080/api/city
新增城市信息
POST https://127.0.0.1:8080/api/city
更新城市信息
PUT https://127.0.0.1:8080/api/city
刪除城市信息
DELETE https://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)
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); } }
代碼詳解:
@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這種校驗。還有各種業務場景。
最後更新:2017-05-19 10:24:31