查看Apache Struts2的帮助文档,关于对s:doubleselect标签的介绍太肤浅,根本不能满足实质的需要.通过文档及网络上的一些介绍,发现文字介绍太繁琐,不如举例说明它的使用方法要简单得多.
首先要保证两个有关联关系的对象:
学生类,Student.java
public class Student { public Integer id; private String name; private Clazz clazz; public Student(Integer id,String name,Clazz clazz) { this.id = id; this.name = name; this.clazz = clazz; } //getter and setter... }
班级类,Clazz.java
public class Clazz { public Integer id; private String className; public Clazz(Integer id,String className) { this.id = id; this.className = className; } //getter and setter... }
Action中的execute方法可以这样写:
public String execute() throws Exception { Clazz clazz1 = new Clazz(1,"一年级"); Clazz clazz2 = new Clazz(1,"二年级"); List clazzList = new ArrayList(); clazzList.add(clazz1);clazzList.add(clazz2); Student user1 = new Student(1,"Tim",clazz1); Student user2 = new Student(1,"Kitty",clazz1); List userList1 = new ArrayList(); userList1.add(user1);userList1.add(user2); Student user3 = new Student(1,"Peter",clazz2); Student user4 = new Student(1,"Tom",clazz2); List userList2 = new ArrayList(); userList2.add(user3);userList2.add(user4); Map map = new HashMap(); map.put(clazz1, userList1);map.put(clazz2, userList2);//理解此处很重要 request.setAttribute("clazzList", clazzList); request.setAttribute("map", map); return "success"; }
标签可以这配置:
<s:doubleselect list="#request.clazzList" listKey="id" listValue="className" doubleName="userId" doubleId="userId" doubleList="#request.map.get(top.id)" <!-- 此处很重要 --> doubleListKey="id" doubleListValue="name"/>
显示效果就是第一个下拉式列表会出现"一年级","二年级",当选择"一年级"时第二个下拉式列表会显示"Tim"和"Kitty",当选择"二年级"时,则会显示"Peter"和"Tom".当把此标签放到form表单里,提交到后台时传递的是一个参数名叫"userId"的字符串数据,即此名字由 doubleName 指定,而get(top.id)的意思是用从第一个下拉式列表中选定的数据来联动显示第二个下拉式列表中的数据(联动数据通过后台代码"map.put(clazz1, userList1);map.put(clazz2, userList2);"来完成).