環境:SpringBoot3.2.5
HTTP PATCH 方法它允許我們對 HTTP 資源進行部分更新。
在篇文章,將帶你如何使用 HTTP PATCH 方法和 JSON Patch文檔格式對 RESTful 資源進行部分更新。
HTTP PATCH 請求正文(Request Body)描述了如何修改目標資源以生成新版本。簡而言之,JSON Patch 格式使用 "一系列操作 "來描述應如何修改目標資源。JSON Patch文檔是一個 JSON 對象數組。數組中的每個對象正好代表一個 JSON Patch操作。Request Body請求格式如下:
[ { "op": "replace|add|remove|move|copy|test", "path": "/xxx", ["value": "value"], ["from": "/yyy"] }, ...]
op:具體的操作
path:資源路徑
value:變更值;根據操作op不同,決定是否有該屬性
from:資源路徑;根據操作op不同,決定是否有該屬性
接下來,通過具體的示例來了解 JSON Patch操作。
接下來的所有操作都基于下面的資源進行:
{ "id": 1, "telephone": "001-555-1234", "favorites": ["Milk","Eggs"], "communicationPreferences": {"post":true, "email":true}}
假設有上面的資源數據,下面將分別介紹基于該資源如何進行不同的操作。
添加操作為對象添加新值。此外,我們還可以用它來更新現有成員,并在指定索引處向數組中插入一個新值。
給favorities數據添加新值,并且插入到第一個位置。
{ "op": "add", "path": "/favorites/0", "value": "Bread"}
{ "id": "1", "telephone": "001-555-1234", "favorites": ["Bread","Milk","Eggs"], "communicationPreferences": {"post":true, "email":true}}
不僅可以刪除指定屬性的值,如果是數組還可以刪除指定索引位置的元素。
刪除communicationPreferences屬性值
請求Body
{ "op": "remove", "path": "/communicationPreferences"}
結果
{ "id": "1", "telephone": "001-555-1234", "favorites": ["Bread","Milk","Eggs"], "communicationPreferences": null}
將目標屬性值更新為一個新的值;
更新電話號碼;
{ "op": "replace", "path": "/telephone", "value": "001-555-5678"}
{ "id": "1", "telephone": "001-555-5678", "favorites": ["Bread","Milk","Eggs"], "communicationPreferences": null}
移動操作會移除指定位置的值,并將其添加到目標位置。
移動favorities屬性第0號位置元素到最后一個位置。
{ "op": "move", "from": "/favorites/0", "path": "/favorites/-"}
{ "id": "1", "telephone": "001-555-5678", "favorites": ["Milk","Eggs","Bread"], "communicationPreferences": null}
復制操作將指定位置的值復制到目標位置。
將favorites屬性中的Milk復制一份到該屬性的最后位置。
{ "op": "copy", "from": "/favorites/0", "path": "/favorites/-"}
{ "id": "1", "telephone": "001-555-5678", "favorites": ["Milk","Eggs","Bread","Milk"], "communicationPreferences": null}
測試操作測試 "路徑 "上的值是否等于 "值"。
{ "op": "test", "path": "/telephone", "value": "001-555-5678"}
注意:JSON Patch請求的Content-Type類型為:application/json-patch+json
接下來將實戰演示在Spring Boot中如何使用JSON Patch。
<dependency> <groupId>com.github.java-json-tools</groupId> <artifactId>json-patch</artifactId> <version>1.13</version></dependency>
該組件是RFC 6902(JSON Patch)和RFC 7386(JSON Merge Patch)的實現,其核心使用Jackson(2.2.x)。該組件的特性:
接下來進入實踐代碼的編寫
public class Customer { /**編號*/ private Long id ; /**電話*/ private String telephone ; /**收藏集*/ private List<String> favorites ; /**通信首選項*/ private Map<String, Boolean> communicationPreferences ; public Customer(Long id, String telephone, List<String> favorites, Map<String, Boolean> communicationPreferences) { this.id = id ; this.telephone = telephone ; this.favorites = favorites ; this.communicationPreferences = communicationPreferences ; } // getters, setters}
public static class CustomerNotFoundException extends RuntimeException {}
當沒有資源時拋出該異常類
@Servicepublic static class CustomerService { // 模擬靜態數據 private static List<Customer> DATAS = List .of(new Customer( 1L, "188", List.of("Milk", "Eggs"), Map.of("phone", true, "email", true))); // 根據ID查詢操作 public Optional<Customer> findCustomer(Long id) { return DATAS.stream().filter(customer -> customer.getId() == id).findFirst(); }}
接下來就是關鍵的Controller接口的編寫了
@PatchMapping(path = "/{id}", consumes = "application/json-patch+json")public ResponseEntity<Customer> updateCustomer(@PathVariable Long id, @RequestBody JsonPatch patch) { try { // 查詢資源 Customer customer = customerService.findCustomer(id).orElseThrow(CustomerNotFoundException::new); Customer customerPatched = applyPatchToCustomer(patch, customer); return ResponseEntity.ok(customerPatched); } catch (JsonPatchException | JsonProcessingException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } catch (CustomerNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); }}// 將請求的操作轉換成真實的資源變更private Customer applyPatchToCustomer(JsonPatch patch, Customer targetCustomer) throws JsonPatchException, JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper() ; JsonNode patched = patch.apply(objectMapper.convertValue(targetCustomer, JsonNode.class)); return objectMapper.treeToValue(patched, Customer.class);}
在該接口中注意以下兩點:
接下來進行測試:
圖片
請求Body中定義了2個操作,replace與add。最后返回的結果表明操作成功,數據得到了變更。
本文鏈接:http://www.tebozhan.com/showinfo-26-112718-0.htmlREST API中的Patch請求大家都用錯了,這才是正確姿勢
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com