SpringMVC接收List型參數


1、controller

@RequestMapping("/postList")
    @ResponseBody
    public String postList(@RequestBody List<TestL> testL){
        System.out.println(testL);
        return null;
    
    }

需要注意點:參數前面必須有注解 @RequestBody

2、ajax請求

var testList=[];
var user={};
user.id=1;
user.name='jack';
testList.push(user);
var user2={};
user2.id=2;
user2.name='tom';
testList.push(user2);
$.ajax({
    // headers必須添加,否則會報415錯誤
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
  type: 'POST',
  dataType: "json", //表示返回值類型,不必須
  data: JSON.stringify(testList),
  url: '/test/postList',
  success: function(){
      alert('success');
  }
  
});

需要注意點:1、參數是數組類型

      2、傳入data時,轉換 JSON.stringify(testList)

      3、必須有headers: {

         'Accept': 'application/json',         'Content-Type': 'application/json'         }

最后再看下TestL類,沒有特別之處(不用包裝)。
public class TestL {
    private Integer id;
    private String name;
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}

 

 


免責聲明!

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



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