Spring 接收表單List集合資料

不知為何就叫呵呵發表於2016-11-28

4種方法,詳情見:http://blog.csdn.net/lutinghuan/article/details/46820023

第一種:

1.新增類,其中有屬性為該物件的集合

public class SettingModel {
    private List<Setting> sets;

    public final List<Setting> getSets() {
        return sets;
    }

    public final void setSets(List<Setting> sets) {
        this.sets = sets;
    }

    @Override
    public String toString() {
        return "SettingModel [sets=" + sets + "]";
    }
    
}

2.表單欄位name屬性值為陣列形式:

<form action="/user/submitUserList_2" method="post">
        ID:<input type="text" name="users[0].id"><br/>
        Username:<input type="text" name="users[0].name"><br/>
        Password:<input type="text" name="users[0].pwd"><br/><br/>

        ID:<input type="text" name="users[2].id"><br/>
        Username:<input type="text" name="users[2].name"><br/>
        Password:<input type="text" name="users[2].pwd"><br/><br/>
        <input type="submit" value="Submit">
</form>

3.後臺接收:

@RequestMapping("/update")
public void update(SettingModel users){ 
  System.out.println(sets);
}

 第二種:

1.ajax請求,POST請求、'Content-Type' : 'application/json;charset=utf-8'、data:json(例如:[{"id":"1","content":"14"},{"id":"2","content":"測試修改2"}])

$.ajax({
                url:'/update',
                type:'POST',
                headers : {  
                        'Content-Type' : 'application/json;charset=utf-8'  
                    },
                dataType:"json",
                data:datastr,//datastr=JSON.stringify(datastr);轉換為JSON格式
                success: function(data){
                    alert('111');
                }
});    

2.後臺接收:

@RequestMapping(value="/update")
    public void update(@RequestBody List<Setting> sets){
        System.out.println(sets);
    }

 

相關文章