vue項目post、put、delete、get向java后端傳數組


通常我們向后端發送數據有兩種方式 get、post,后又restful風格出現,又有put、delete等傳參方式。但是對於我們來說他們的傳參本質還是只有get和post的兩種,即 get、delete是一樣的方式、post、put是一樣的。

在vue項目中,通常使用axios發送ajax請求於是就有下面兩種情況傳數組

一、get、delete傳數組

我們這里需要一個json插件qs

 params:{
          ids: [1,2,3,4],
 },
 paramsSerializer:function (params) {
           return qs.stringify(params, {indices: false })
}

java后端直接用數組接收即可   例如:

 @DeleteMapping("delAny") | @GetMapping("delAny")
  public int delOneById(Long[] ids) {
        return service.delByIds(Arrays.asList(ids));
  }

二、post、put等傳數組

 this.axios.post('/sysUser/addOne', {
         username: this.addUser.username,
         realName: this.addUser.realName,
         phone: this.addUser.phone,
         roles: JSON.stringify(this.addUser.selectRoles)
})

上訴代碼中的參數 roles是數組,這里我並還有直接將數組傳參到后端,而是將其JSON化,轉換成為JSON字符串,於是后端接收的也是一個字符串

@PostMapping("addOne")
public int addOne(String username, String realName, String phone, String roles) {
     //轉換字符串為json數組 JSONArray json
= JSONObject.parseArray(roles);
     //創建一個數組對象 長度和json數組一樣 即json.size() Integer[] a
= new Integer[json.size()];
     //然后將之轉換成我們需要的數組就好了 json.stream().forEach(System.out::println); Integer[] array
= json.toArray(a); return service.addOne(username, realName, phone, array); }

這里我使用到了阿里的fastjson作為操作json的工具。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM