1. 程式人生 > >SSM整合系列之 實現RESTFul API

SSM整合系列之 實現RESTFul API

摘要:REST,即Representational State Transfer的縮寫。直接翻譯的意思是"表現層狀態轉化"。它是一種網際網路應用程式的API設計理念:URL定位資源,用HTTP動詞(GET,POST,DELETE,PUT)描述操作。本文將介紹Restful風格API在SSM系統中的使用,我將實現如下幾種常用風格的API

  GET    --> /ssm/basicUser/1            檢視某個具體的使用者
  POST   --> /ssm/basicUser/user         新建一個使用者
  PUT    --> /ssm/basicUser/1            更新某個具體的使用者
  DELETE --> /ssm/basicUser/1            刪除某個具體的使用者

在開始實現案例之前簡單介紹下相關概念

1. REST原則,圍繞資源展開介紹
從資源的定義、獲取、表述、關聯、狀態變遷等角度,列舉一些關鍵概念並加以解釋。
(1.1)資源與URI
其實指的就是資源。任何事物,它就是一個資源。資源可以是實體(使用者),也可以只是一個抽象概念(例如使用者價值)
(1.2)統一資源介面
RESTful架構應該遵循統一介面原則,統一介面包含了一組受限的預定義的操作,不論什麼樣的資源,都是通過使用相同的介面進行資源的訪問。介面應該使用標準的HTTP方法如GET,PUT和POST,並遵循這些方法的語義。
(1.3)資源的表述
介面請求,客戶端獲取的可以說是資源的表述而已。 資源在外界的具體呈現,可以有多種表述形式,在客戶端和服務端之間傳送的也是資源的表述,而不是資源本身。 如文字的html、xml、json等格式,圖片可以使用PNG或JPG展現出來
(1.4)狀態的轉移


類似"下一頁"之類的連結起的就是這種推進狀態的作用——指引你如何從當前狀態進入下一個可能的狀態

2. SSM系統構建RESTFul API
(2.1)GET 檢視使用者具體實現

package com.ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.entity.BasicUser;
import com.ssm.entity.Page;
import com.ssm.service.BasicUserService;
import com.ssm.util.FinalData;
import com.ssm.util.ResultModel;

/**
 * 使用者控制器
 * @author https://blog.csdn.net/caiqing116
 */
@Controller
@RequestMapping("/ssm/basicUser")
public class BasicUserController {
	
	@Autowired 
	private BasicUserService basicUserService;

	/**
	 * 查
	 * @param id 使用者id
	 * @return
	 */
	@RequestMapping(value="/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel selectById(@PathVariable("id")Integer id) {
		BasicUser basicUser = basicUserService.selectById(id);
		return new ResultModel(200, basicUser, "獲取成功");
	}
}

(2.2)POST 建立使用者具體實現

/**
 * 增
 * @param basicUser 使用者物件
 * @return
 */
@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseBody
public ResultModel insertBasicUser(BasicUser basicUser) {
	int row = basicUserService.insert(basicUser);
	if(row > 0) {
		return new ResultModel(201, row, "新增成功");
	}
	return new ResultModel(200, row, "新增失敗");
}

(2.3)PUT更新某個使用者實現
對應put和delete請求需要在web.xml檔案中配置過濾器,在請求時使用POST請求,額外傳遞引數 _method=”PUT"

<!-- 配置過濾器 將POST請求轉換為PUT和DELETE請求 -->
  <filter>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
      <filter-name>HiddenHttpMethodFilter</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>

更新某個使用者實現

 * 改
 * @param id 使用者id
 * @param realname 使用者真實姓名
 * @return
 */
@RequestMapping(value="/{id}", method = RequestMethod.PUT)
@ResponseBody
public ResultModel updateById(@PathVariable("id")Integer id, String realname) {
	BasicUser basicUser = new BasicUser();
	basicUser.setId(id);
	basicUser.setRealname(realname);
	int row = basicUserService.updateById(basicUser);
	if(row > 0) {
		return new ResultModel(201, row, "更新成功");
	}
	return new ResultModel(200, row, "更新失敗");
}

(2.4)DELETE刪除使用者具體實現
在請求時使用POST請求,額外傳遞引數 _method=”DELETE"

/**
 * 刪
 * @param id 使用者id
 * @return
 */
@RequestMapping(value="/{id}", method = RequestMethod.DELETE)
@ResponseBody
public ResultModel deleteById(@PathVariable("id")Integer id) {
	int row = basicUserService.deleteById(id);
	if(row > 0) {
		return new ResultModel(200, row, "刪除成功");
	}
	return new ResultModel(404, row, "刪除失敗");
}

3. 錯誤碼總結

GET錯誤碼

200(OK) - 表示已在響應中發出
204(無內容) - 資源有空表示
301(Moved Permanently) - 資源的URI已被更新
303(See Other) - 其他(如,負載均衡)
304(not modified)- 資源未更改(快取)
400 (bad request)- 指代壞請求(如,引數錯誤)
404 (not found)- 資源不存在
406 (not acceptable)- 服務端不支援所需表示
500 (internal server error)- 通用錯誤響應
503 (Service Unavailable)- 服務端當前無法處理請求

POST錯誤碼

200(OK)- 如果現有資源已被更改
201(created)- 如果新資源被建立
202(accepted)- 已接受處理請求但尚未完成(非同步處理)
301(Moved Permanently)- 資源的URI被更新
303(See Other)- 其他(如,負載均衡)
400(bad request)- 指代壞請求
404 (not found)- 資源不存在
406 (not acceptable)- 服務端不支援所需表示
409 (conflict)- 通用衝突
412 (Precondition Failed)- 前置條件失敗(如執行條件更新時的衝突)
415 (unsupported media type)- 接受到的表示不受支援
500 (internal server error)- 通用錯誤響應
503 (Service Unavailable)- 服務當前無法處理請求

PUT錯誤碼

200 (OK)- 如果已存在資源被更改
201 (created)- 如果新資源被建立
301(Moved Permanently)- 資源的URI已更改
303 (See Other)- 其他(如,負載均衡)
400 (bad request)- 指代壞請求
404 (not found)- 資源不存在
406 (not acceptable)- 服務端不支援所需表示
409 (conflict)- 通用衝突
412 (Precondition Failed)- 前置條件失敗(如執行條件更新時的衝突)
415 (unsupported media type)- 接受到的表示不受支援
500 (internal server error)- 通用錯誤響應
503 (Service Unavailable)- 服務當前無法處理請求

DELETE錯誤碼

200 (OK)- 資源已被刪除
301 (Moved Permanently)- 資源的URI已更改
303 (See Other)- 其他,如負載均衡
400 (bad request)- 指代壞請求
404 (not found)- 資源不存在
409 (conflict)- 通用衝突
500 (internal server error)- 通用錯誤響應
503 (Service Unavailable)- 服務端當前無法處理請求