Struts标签动态赋值并赋默认值

一、Struts标签<html:select>动态赋值并赋默认值
1.ID和名称定义两个集合
Action方法:
List fristdeptlist = docDao.getFristDept();
  List deptidlist=new ArrayList();
  for(int i=0;i<fristdeptlist.size();i++){
   TblDept tbldept=(TblDept)fristdeptlist.get(i);
   deptidlist.add(tbldept.getDtid());
  }
  List deptnamelist=new ArrayList();
  for(int i=0;i<fristdeptlist.size();i++){
   TblDept tbldept=(TblDept)fristdeptlist.get(i);
   deptnamelist.add(tbldept.getDeptname());
  }
request.setAttribute("deptidlist", deptidlist);
request.setAttribute("deptnamelist", deptnamelist);

jsp页面:
<html:select name="docForm" property="firstdtid">
       <html:options name="deptidlist" labelName="deptnamelist" />
</html:select>

2.ID和名称定义LabelValueBean对象
Action方法:
ArrayList difficultyList=new ArrayList();
String[] tmp1 = StatusClass.DIFFICULTS;
for(int n=0;n<tmp1.length;n++){
       String tmpstr = tmp1[n];
       String[] tmp2 = tmpstr.split(",");
       difficultyList.add(new LabelValueBean(tmp2[1],tmp2[0]));
}
request.setAttribute("difficultyList", difficultyList);

jsp页面:
<html:select property="difficulty">
       <html:optionsCollection name="difficultyList" />
</html:select>


二、总结Struts中<html:select>标签绑定值的三种方法
1.固定的值的写法
<html:select property="enjoyDevelop">
   <html:option value="喜欢">喜欢</html:option>
   <html:option value="不喜欢">不喜欢</html:option>
</html:select>

2.非固定的两种写法(支持数据库中值绑定)
绑定数组:
<html:select property="enjoyDevelop">
   <html:options property="enjoyDevelops" labelProperty="enjoyDevelopsLable"/>
</html:select>
property:指定值的内容
labelProperty:指定显示内容的
指定的属性代码:(分别生成get和set方法)
private String[] enjoyDevelops = new String[]{"very enjoy","just so so","don't like","hate"};
private String[] enjoyDevelopsLable = new String[]{"非常喜欢","一般般","不喜欢","讨厌"};

3.绑定一个集合:
<html:select property="enjoyDevelop">
   <html:optionsCollection property="enjoyDevelopList" value="value" label="text"/>
</html:select>
property:指定要绑定的List对象名
value:指定HashMap中的value
label:指定HashMap中的text
在ActionForm中的get方法:
public List getEnjoyDevelopList() {
   List enjoyDevelopList = new ArrayList();
   for (int i = 0; i < enjoyDevelops.length; i++) {
        Map map = new HashMap();
        map.put("value",enjoyDevelops[i]);
        map.put("text",enjoyDevelopsLable[i]);
        enjoyDevelopList.add(map);
      }
   return enjoyDevelopList;
}

你可能感兴趣的:(html,struts)