我的问题情境是这样的:
前台有几组复选框,每个框都对应一个id,只有在选中了该复选框之后,该复选框对应的id才会传递到后台action中,后台需要接受到一个id数组。
问题解决的关键:
1.我利用Struts2的set和get方法自动注入参数,是无法直接传递数组的,Struts2会自动将前台的数组自动装配为以“, ”隔开的字符串(注意是以逗号加空格符隔开)。因此在后台接受时,只能定义一个字符串,然后通过spilt()方法解析一下该字符串,将该字符串转化为对应的数组。
2.JSP页面会自动判断对应的复选框是否选中,选中才会将对应的id传递到后台,未选中就不会传递对应的id。
具体代码:
1.jsp页面代码:
<span style="font-size:14px;">...
<form action="Update?ModuleID=<%=1%>" method="post" id="form1" name="form1">
<td><input type="submit" value="更新" οnclick="return show()"></td>
<td width="80px">工作动态</td>
<%
for(int i = 0 ; i < GzdtPara.size() ; i++){
String[] strs = GzdtPara.get(i);
String id = strs[0];
String name = strs[1];
%>
<td><input name="WebIDs" id="WebIDs" type="checkbox" value="<%=id%>"/><%=name%></td>
<%} %>
</form>
...
...
function show( ) {
var checkObj = document.all("WebIDs");
var j=0;
for(var i = 0;i < checkObj.length;i++) {
if(checkObj[i].checked == true){
j++;
}
}
if(j != 0) {
showWindow('友情提示','数据更新中,请耐心等待...',200,300);
return true;
}else {
alert("请至少选择一个复选框");
return false;
}
} </span>
2.后台代码
model:
<span style="font-size:14px;">public class UpdateModel {
private String ModuleID;
private String WebIDs;
public String getModuleID() {
return ModuleID;
}
public void setModuleID(String moduleID) {
ModuleID = moduleID;
}
public String getWebIDs() {
return WebIDs;
}
public void setWebIDs(String webIDs) {
WebIDs = webIDs;
}
}</span>
Action:
public class UpdateAction extends UpdateModel implements ServletRequestAware, Action {
public String Update() {
String strWebId = this.getWebIDs();
//“,”后面带了一个空格
String[] strsWebId = strWebId.split(",");
int[] intsWebId = new int[strsWebId.length];
for (int i = 0; i < strsWebId.length; i++) {
//trim()截去前后空格
intsWebId[i] = Integer.valueOf(strsWebId[i].trim());
}
... ...
... ...
return SUCCESS;
}