Spring MVC 多选框 绑定 Entity 中的 list 属性

时间:2022-06-29 10:22:10

问题描述:

有两个类:Record.java 和 User.java,Record中有个attenders属性,是List<User>类型。

我想绑定Record中的attenders。网上查了下,没有满意的结果,于是自己写了个简单的方法。

具体代码如下:

Record.java

public class Record {

    public List<User> getAttenders() {
return attenders;
}
public void setAttenders(List<User> attenders) {
this.attenders = attenders;
}
public int getRecordId() {
return recordId;
}
public void setRecordId(int recordId) {
this.recordId = recordId;
} public String getRecordName() {
return recordName;
}
public void setRecordName(String recordName) {
this.recordName = recordName;
} private List<User> attenders;
private int recordId;
private String recordName; }

User.java

public class User {

    public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
private int userId;
private String userName; }

MultiSelect.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<title>main page</title>
<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript">
function check(){
var index = ;
$.each(
$('#attenderSelect :selected'),function(){
var input = $('<input>');
input.attr("name","attenders["+index+"].userId");
input.attr("type","hidden");
input.attr("value",$(this).val());
$('#attenderSelect').append(input);
index ++;
}
);
} </script> </head>
<body> <input name="" type="hidden" value=""> <form:form action="./user.htm?method=multiSelect" method="post">
<table>
<tr>
<td>
<select id="attenderSelect" name="attenders.userId" multiple="multiple">
<c:forEach var="user" items="${userList }">
<option value="${user.userId}" >${user.userName }</option>
</c:forEach>
</select>
</td>
</tr> <tr>
<td>
<input type="text" name="recordName">
</td>
</tr> <tr>
<td>
<input type="submit" value="submit" onclick="check()">
</td>
</tr> </table>
</form:form> </body>
</html>

Controller method:

public class UserFormController extends MultiActionController {

    public ModelAndView multiSelect(HttpServletRequest request,
HttpServletResponse response) throws Exception { Record record = (Record) newCommandObject(Record.class);
bind(request,record); // if(record.getAttenders() != null)
// for(User user : record.getAttenders()){
// System.out.println(user.getUserId());
// } ModelAndView mav = new ModelAndView("index");
return mav; }
}  

通过在提交表单时,创建一些隐藏的 input ,并命名为 attenders[index].userId,这样就达到了将数据绑定到对象的目的了