今天遇到一个问题就是,如何设置<html:select>多选情况下的默认值,网上有些人说下面是可行的:
<html:form action="/projectUpdate.do" focus="experimenters">
<html:select property="experimenters" size="10" multiple="true" value="experimenters">
<html:optionsCollection
name="msms_experimenterlist" value="email" label="email"/>
</html:select>
....
</html:form>
这里,experimenters是projectForm的属性,类型为String[]
msms_experimenterlist是保存在request中的一个set<UserInfo>,email是UserInfo的属性,类型为String。
显示以及传递到/projectUpdate.do对应的Action都正常,但是如果给projectForm的experimenters设置了初始值,在真实显示的时候,多选框中并没有设置这些初始值,很是麻烦。
虽然最后通过jsp的方法解决,总是不爽阿:
<html:select property="experimenters" size="10" multiple="true" value="experimenters">
<%ProjectForm projForm = (ProjectForm) request.getAttribute("projectForm");
HashSet<String>
oldExperimenters = new
HashSet<String>(Arrays.asList(projForm.getExperimenters()));
List userList = (List)request.getAttribute("msms_experimenterlist");
for(int i = 0;i < userList.size();i++){
UserInfo user = (UserInfo) userList.get(i);
if (oldExperimenters.contains(user.getEmail())){
out.print("<option value=\"" + user.getEmail() + "\" selected>" +
user.getEmail());
}
else{
out.print("<option value=\"" + user.getEmail() + "\">" +
user.getEmail());
}
}
%>
</html:select>