天天看點

Springboot 實作 Restful 服務,基于 HTTP / JSON 傳輸

“怎樣的人生才是沒有遺憾的人生?我的體會是:(1)擁有健康;(2)創造“難忘時刻”;(3)盡力做好自己,不必改變世界;(4)活在當下。” – 《向死而生》李開複

基于上一篇《springboot 整合 mybatis 的完整 web 案例》,這邊我們着重在 控制層 講講。講講如何在 springboot 實作 restful 服務,基于 http / json 傳輸。

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 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

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)

2.spring 對 rest 支援實作

cityrestcontroller.java 城市 controller 實作 restful http 服務

代碼詳解:

@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   請求查詢伺服器的性能,或者查詢與資源相關的選項和需求

springboot 實作 restful 服務,基于 http / json 傳輸,适用于前後端分離。這隻是個小demo,沒有加入bean validation這種校驗。還有各種業務場景。