1 前后端分離時代的技術選擇
現在的Web開發,前后端分離已經不是什么新鮮事了。前端用什么?很多團隊選擇Axios。后端呢?Java Spring依然是企業級應用的首選。
Axios這個JavaScript庫確實好用,Promise-based的設計讓異步請求變得簡單。Java Spring框架在后端領域的地位就更不用說了,穩定、功能強大,特別是Spring Boot出現后,配置工作量大幅減少。
本文會詳細講解Axios怎么發請求,Spring怎么接收處理,涵蓋常見的CRUD操作、搜索功能,還有批量處理這些實際開發中經常遇到的場景。
1.1 為什么選擇Axios
Axios在前端HTTP庫中算是佼佼者,原因很簡單:
異步數據交互方面,Axios讓Ajax請求變得輕松,和后端RESTful API對接毫無壓力。跨域請求支持是原生的,不用額外配置就能處理CORS問題。
請求/響應攔截器這個功能特別實用,可以在請求發出前統一添加token,或者在響應回來后統一處理錯誤。API設計也很人性化,上手快,配置選項豐富。
1.2 Spring框架的企業級優勢
Spring Boot的出現改變了Java后端開發的游戲規則。
約定優于配置這個理念讓開發者從繁瑣的XML配置中解脫出來。想要RESTful API?幾個注解就搞定。需要集成數據庫、安全認證、消息隊列?各種Starter POMs讓這些變得簡單。
配合Spring Cloud,微服務架構也不再是難題。這就是為什么這么多企業選擇Spring的原因。
2 HTTP方法與RESTful設計
理解HTTP方法是做好RESTful API的基礎。每個方法都有自己的用途和特點。
2.1 核心HTTP方法解析
GET - 獲取數據用的,參數放在URL里,冪等且安全,但不適合傳敏感信息,瀏覽器會緩存
POST - 提交數據,創建資源,數據放在請求體里,非冪等
PUT - 更新資源,替換整個資源,冪等
DELETE - 刪除資源,冪等
這些方法對應著數據的增刪改查操作,遵循RESTful設計原則。
3 Axios與Spring Boot基礎對接
3.1 Axios快速上手
安裝很簡單:
npm install axios
# 或者
yarn add axios
基本用法:
import axios from 'axios';axios.get('http://localhost:8080/api/data').then(response => {console.log(response.data);}).catch(error => {console.error("獲取數據失敗", error);});
3.2 Spring Boot項目搭建
環境要求:JDK 8+,Maven或Gradle。
用Spring Initializr (https://start.spring.io/) 生成項目骨架最方便。
寫個簡單的Controller:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class DataController {@GetMapping("/api/data")public String getData() {return "Hello from Spring Boot!";}
}
運行項目:mvn spring-boot:run
或 gradlew bootRun
4 實戰場景詳解
4.1 刪除單個資源(路徑參數)
這是最標準的RESTful刪除方式。
前端代碼:
axios.delete(`/delete/${id}`).then(response => {console.log('刪除成功', response.data);}).catch(error => {console.error('刪除失敗', error);});
后端代碼:
@DeleteMapping("/delete/{id}")
public ResponseEntity<String> deleteResource(@PathVariable("id") Long id) {service.deleteById(id);return ResponseEntity.ok("ID為 " + id + " 的資源已刪除");
}
4.2 刪除資源(查詢參數方式)
有時候需要通過查詢參數傳遞ID。
前端代碼:
axios.get('/delete', { params: { id: 11 } }).then(response => {console.log('刪除成功', response.data);}).catch(error => {console.error('刪除失敗', error);});
后端代碼:
@GetMapping("/delete")
public ResponseEntity<String> deleteResourceById(@RequestParam("id") Long id) {service.deleteById(id);return ResponseEntity.ok("ID為 " + id + " 的資源已刪除");
}
注意: 實際項目中別用GET做刪除操作,不符合REST規范,而且有安全風險。
4.3 更新資源(POST方式)
前端代碼:
axios.post('/update', { id: 1 }).then(response => {console.log('更新成功', response.data);}).catch(error => {console.error('更新失敗', error);});
后端代碼:
@PostMapping("/update")
public ResponseEntity<String> updateResource(@RequestBody ResourceUpdateRequest request) {Long id = request.getId();service.updateResource(id);return ResponseEntity.ok("ID為 " + id + " 的資源已更新");
}
4.4 完整更新資源(PUT方式)
PUT用于完整替換資源。
前端代碼:
axios.put('/update', { id: 1, newName: '新名稱' }).then(response => {console.log('更新成功', response.data);}).catch(error => {console.error('更新失敗', error);});
后端代碼:
@PutMapping("/update")
public ResponseEntity<String> updateResourceCompletely(@RequestBody ResourceUpdateRequest request) {Long id = request.getId();String newName = request.getNewName();service.updateResourceCompletely(id, newName);return ResponseEntity.ok("ID為 " + id + " 的資源已完全更新");
}
4.5 創建新資源
前端代碼:
axios.post('/create', { name: '新資源' }).then(response => {console.log('創建成功', response.data);}).catch(error => {console.error('創建失敗', error);});
后端代碼:
@PostMapping("/create")
public ResponseEntity<ResourceCreatedResponse> createNewResource(@RequestBody NewResourceRequest request) {String resourceName = request.getName();ResourceCreatedResponse response = service.createNewResource(resourceName);return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
4.6 搜索功能實現
搜索通常用GET請求,參數通過URL傳遞。
前端代碼:
axios.get('/search', { params: { keyword: '關鍵詞' } }).then(response => {console.log('搜索結果:', response.data);}).catch(error => {console.error('搜索失敗', error);});
后端代碼:
@GetMapping("/search")
public ResponseEntity<List<Resource>> searchResources(@RequestParam("keyword") String keyword) {List<Resource> results = service.searchByKeyword(keyword);return ResponseEntity.ok(results);
}
4.7 批量刪除操作
批量操作需要傳遞多個ID,用DELETE請求體。
前端代碼:
axios.delete('/batchDelete', { data: [{ id: 1 }, { id: 2 }] }).then(response => {console.log('批量刪除成功', response.data);}).catch(error => {console.error('批量刪除失敗', error);});
后端代碼:
@DeleteMapping("/batchDelete")
public ResponseEntity<String> batchDeleteResources(@RequestBody List<Long> ids) {service.batchDelete(ids);return ResponseEntity.ok("ID為 " + ids + " 的資源已批量刪除");
}
提醒: Axios的delete方法默認不支持請求體,要用
axios({ method: 'delete', url: '/...', data: yourData })
這種寫法。
5 HTTP方法與注解對應關系
5.1 各種請求的處理方式
GET請求 - 獲取資源或搜索,用@GetMapping
+ @PathVariable
或@RequestParam
POST請求 - 創建資源或提交數據,用@PostMapping
+ @RequestBody
PUT請求 - 完整更新資源,用@PutMapping
+ @RequestBody
DELETE請求 - 刪除資源,用@DeleteMapping
+ @PathVariable
或@RequestBody
6 開發中的注意事項
6.1 安全方面的考慮
別用GET做修改操作
GET請求可能被瀏覽器預加載、緩存,或者留在瀏覽歷史里。修改數據要用POST、PUT、DELETE。
敏感數據要加密
不管用什么HTTP方法,敏感數據傳輸都要用HTTPS。
做好認證和授權
OAuth、JWT這些認證機制要用起來,確保只有合法用戶能訪問和修改數據。
6.2 性能優化建議
異步處理
前端用Ajax異步請求,避免頁面刷新,用戶體驗更好。后端也可以用異步編程處理耗時操作。
緩存策略
靜態資源和不常變的數據要設置緩存,ETag、Last-Modified、Cache-Control這些HTTP頭要用好。
分頁和懶加載
大量數據要分頁顯示,需要時再加載,減少首次加載時間。
數據壓縮
開啟GZIP壓縮,特別是文本數據,能明顯減少傳輸量。