首頁  >  文章  >  Java  >  SpringMVC傳遞陣列請求問題的詳情與解決

SpringMVC傳遞陣列請求問題的詳情與解決

黄舟
黄舟原創
2017-03-04 09:26:301598瀏覽

在使用SpringMVC時,我們想傳遞數組引用類型,SpringMVC對數組傳遞有些限制:

經過測試:SpringMVC支援一維數組的參數傳遞,不支援多維數組的參數傳遞,如果想傳遞多維數組,那麼我們只好改用其他的辦法如:1、將多維數組拆成一維數組;2、將多維數組改為集合傳遞;3、或者改為字串,接收時間處理一下等等,4 、或將所有陣列中的值拼接傳遞(例如:data=1&data=2&data=3,代表三個陣列的值)方法很靈活。

1 SpringMVC傳遞一維數組:傳遞數組類型時,需要在@requestParam()中加入value,否則會出現HTTP Status 400 - Required long[] parameter 'data' is not present錯誤。

    例如: @RequestParam(value = "data[]")long[] data

   

##   前端請求:


   前端請求:

var dataArr = new Array();  
        for(var i = 0; i < 10; i++){  
            dataArr.push(i);  
        }  
        $.ajax({  
                url : "test/arrayParam.shtml",  
                data : {  
                    "datas" : dataArr  
                },  
                dataType : "json",  
                success : function(data) {  
                    alert(data);  
                },  
                async : false  
            });  
        }


後端程式碼:

  • #

    package com.pyc.search.view.controller;  
      
    import org.springframework.stereotype.Controller;  
    import org.springframework.web.bind.annotation.RequestMapping;  
    import org.springframework.web.bind.annotation.RequestParam;  
    import org.springframework.web.bind.annotation.ResponseBody;  
      
    /** 
     * 创建时间:2014-12-24 上午11:52:00 
     *  
     * @author zhangtianyou 
     */  
    @Controller  
    @RequestMapping("/test")  
    public class TestController {  
      
        @RequestMapping("/arrayParam")  
        public @ResponseBody  
        int test1(@RequestParam(value = "datas[]") long[] datas) {  
      
            return datas.length;  
        }  
    }




#2 多維數組可以轉換為一維數組,或轉換為字串,在後端接收時處理一下。

 以上就是SpringMVC傳遞陣列請求問題的詳情和解決的內容,更多相關內容請關注PHP中文網(www.php.cn)! ################
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn