利用SpringMVC参数绑定实现动态插入数据

javabean代码:
public class User { private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } public class UserListForm { private List<User> users; public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } }
springmvc控制器访问入口:
@RequestMapping("saysth.do")
public void test(UserListForm userForm) {
    for (User user : userForm.getUsers()) {
        System.out.println(user.getFirstName() + " - " + user.getLastName());
    }
}

html 代码:

<form action="saysth.do" method="post">
<input id="rowCount" name="rowCount" value="0" />
<table id="tblShopData"> <thead>
<tr> <th>First Name</th> <th>Last Name</th> </tr> </thead>
<tfoot> <tr> <td colspan="2"><input type="submit" value="Save" /></td> </tr>
</tfoot> <tbody>
<tr id="tShopRow0">
<td><input id="users[0].firstName" name="users[0].firstName" /></td>
<td><input id="users[0].lastName" name="users[0].lastName" /></td>
</tr>
</tbody>
</table><a href="#" onclick="addShopRow()">添加一行</a>&nbsp;&nbsp;<a href="#" onclick="delShopRow()">删除一行</a>

</form>

js代码:

//添加行
function addShopRow(){
var num=$("#rowCount").val();//取值
num=parseInt(num);
num++;
$("#tShopRow0").clone(true).attr("id","tShopRow"+num).appendTo("#tblShopData");
$("#tShopRow"+num+" td").each(function(){
$(this).find("input[type='text']").val("");//清空数据
$(this).find("input[name='users[0].firstName']").attr("id","users['"+num+"'].firstName").attr("name","users['"+num+"'].firstName");
$(this).find("input[name='users[0].lastName']").attr("id","users['"+num+"'].platformName").attr("name","users['"+num+"'].lastName");
});
$('#rowCount').val(num);//重新赋值
}
//删除行
function delShopRow(){
var num=$("#rowCount").val();//取值
num=parseInt(num);
if(num>0){
$("#tShopRow"+num).remove();
num--;
$('#rowCount').val(num);//重新赋值
}else{
alert("这是第一行了!");
}
}



posted @ 2016-11-12 18:59  _推前浪  阅读(2887)  评论(1编辑  收藏  举报