“怎樣的人生才是沒有遺憾的人生?我的體會是:(1)擁有健康;(2)創(chuàng)造“難忘時刻”;(3)盡力做好自己,不必改變世界;(4)活在當下。”– 《向死而生》李開復
Spring Boot 系列文章:《Spring Boot 那些事》
基于上一篇《Springboot 整合 Mybatis 的完整 Web 案例》,這邊我們著重在 控制層 講講。講講如何在 Springboot 實現(xiàn) Restful 服務(wù),基于 HTTP / JSON 傳輸。
git clone 下載工程 springboot-learning-example ,項目地址見 GitHub – https://github.com/JeffLi1993/springboot-learning-example。下面開始運行工程步驟(Quick Start):
1.數(shù)據(jù)庫準備
a.創(chuàng)建數(shù)據(jù)庫 springbootdb:
CREATE DATABASE springbootdb;
b.創(chuàng)建表 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.插入數(shù)據(jù)
INSERT cityVALUES (1 ,1,'溫嶺市','BYSocket 的家在溫嶺。');
2. springboot-restful 工程項目結(jié)構(gòu)介紹
springboot-restful 工程項目結(jié)構(gòu)如下圖所示:
org.spring.springboot.controller – Controller 層org.spring.springboot.dao – 數(shù)據(jù)操作層 DAOorg.spring.springboot.domain – 實體類org.spring.springboot.service – 業(yè)務(wù)邏輯層Application – 應(yīng)用啟動類application.properties – 應(yīng)用配置文件,應(yīng)用啟動會自動讀取配置
mvn clean install
?
資源(Resource)資源的表述(Representation)狀態(tài)轉(zhuǎn)移(State Transfer)統(tǒng)一接口(Uniform Interface)超文本驅(qū)動(Hypertext Driven)
面向資源(Resource Oriented)可尋址(Addressability)連通性(Connectedness)無狀態(tài)(Statelessness)統(tǒng)一接口(Uniform Interface)超文本驅(qū)動(Hypertext Driven)
CityRestController.java 城市 Controller 實現(xiàn) Restful HTTP 服務(wù)
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);
}
}
method – 指定請求的方法類型:POST/GET/DELETE/PUT 等value – 指定實際的請求地址consumes – 指定處理請求的提交內(nèi)容類型,例如 Content-Type 頭部設(shè)置application/json, text/html
produces – 指定返回的內(nèi)容類型
GET 請求獲取Request-URI所標識的資源
POST 在Request-URI所標識的資源后附加新的數(shù)據(jù)HEAD 請求獲取由Request-URI所標識的資源的響應(yīng)消息報頭PUT 請求服務(wù)器存儲一個資源,并用Request-URI作為其標識DELETE 請求服務(wù)器刪除Request-URI所標識的資源TRACE 請求服務(wù)器回送收到的請求信息,主要用于測試或診斷CONNECT 保留將來使用OPTIONS 請求查詢服務(wù)器的性能,或者查詢與資源相關(guān)的選項和需求
更多建議: