1. 程式人生 > 實用技巧 >SpringBoot 接收前端引數的幾種方式

SpringBoot 接收前端引數的幾種方式

昨天和前端小夥伴在聯調是碰到了引數接收不到的錯誤,我在postman上測試介面是正常的,但是與前端對接時就接受不到引數,請求方式都是get,但是問題就在於json 和form-data 的區別!這是一個SpringBoot+Vue的前後端分離專案

1)如果前端傳的是json,後端接受時要用@RequestBody註解,json物件要與實體類對應

 public boolean updateKnowledge(@RequestBody Knowledge knowledge){
return knowledgeService.updateKnowledge(knowledge);
}

    如果json沒有與實體類對應的話,可以有另外一種方法,利用JSONObject物件取值,可以直接轉換成你需要的型別,這裡僅展示string型別

 public int deleteKnowledge(@RequestBody JSONObject obj){
return knowledgeService.deleteKnowledge(obj.getString("id"));
}

 2)如果前端傳的是form-data,後端接受時要用@RequestParam註解,表單的key也要與實體類的欄位對應

 public void downloadFile( @RequestParam("groupName") String groupName,@RequestParam("url") String url, HttpServletResponse response) throws IOException {
MyFile myFile = new MyFile();
myFile.setGroupName(groupName);
myFile.setUrl(url);
myFileService.downloadFile(myFile,response);
}
如果有什麼疑問歡迎留言,當然我也不一定懂!一起學習一起進步,群876083754