---
title: "关于struts2两级联动的写法"
author: "Passager009"
date: "2014-03-10T08:19:28Z"
tags: []
categories: ["Web前端"]
slug: "struts2"
draft: false
lastmod: "2014-03-10T08:18:29Z"
id: 2028677
url: "https://passager009.iteye.com/blog/2028677"
---

在开发的时候突然遇到需要写个二级联动，而正好我用的是struts2.0，于是就写了一个。废话不多说，直接上代码。

    首先，要在Controller中注册页面二级联动属性，写好get/set方法。在这里我拿 学科-章节-小节 来做练习。利用学科id来得到章节属性。

```
private List<Chapter> chapters;
private Map<Integer,List<Unit>> unitMap;
//省略get/set方法。。。。
public void loadDoubleSelect(){
      
       chapters = chapterService.findBySubject(subjectId);
       unitMap = new LinkedHashMap<Integer, List<Unit>>();
       if(chapters.size()>0){
           for(Chapter chapter:chapters){
	      List<Unit> units = unitService.findByChapter(chapter.getId());
	      unitMap.put(chapter.getId(), units);
	   }
        }
}
```

        其中chapters 是根据学科id获取该学科下的所有章节。unitMap是当前章节下所获取的小节集合，在这里利用键值对进行存贮。

       Controller配置完成，那么进入jsp页面，如上代码所示，在这里进行了数据的准备，那么在获取的时候必须用该Controller所写的属性。

```
<style> 
     .nobr br{display:none}   
       
</style>
<div>
	<s:form method="post" action="/exercise_showList" name="serchForm">
		<s:doubleselect list="chapters" listKey="id" listValue="title" formName="searchForm" headerKey="" headerValue="-请选择-"  name="chapterId" cssStyle="width:120px;"  
			doubleList="unitMap.get(top.id)" doubleName="unitId" doubleListKey="id" doubleListValue="title"   doubleCssStyle="width:120px;">
  		</s:doubleselect>
	</s:form>
</div>
```

    上文中这个style样式是因为什么呢？因为struts2.0中默认样式为两个下拉框在一列上，一上一下。该样式就是解决这个问题的。这样就能获取到Controller的数据。

     我来解释一下&lt;s:doubleselect&gt;中的属性。

```
tooltip指显示图标的显示文字
label 指生成组件前的标签文字
name 指第一个下拉框的表单name属性
list 指第一个下拉框的集合
listKey 指第一个下拉框的选项的键值 提交后天的值 --对应集合里单个对象里面的属性
listValue 指第一个下拉框中的选项显示值 --对应集合里单个对象里面的属
doubleList 指第二个下拉框要使用的集合
doubleName 指第二个下拉框的表单name属性
doubleListKey 指第二个下拉框中的选项中的键值 --对应集合里单个对象里面的属性
doubleListValue 指第二个下拉框中的选项显示值 --对应集合里单个对象里面的属性
在这里注意：formName则这里必须填写该form表单的name值，否则二级联动会失败。
```

    在这里效果图如下所示：

 

![](http://dl2.iteye.com/upload/attachment/0094/5921/e3614c0c-2e86-3419-b3ab-a60544c93e13.png)![](http://dl2.iteye.com/upload/attachment/0094/5919/d5dfaa3c-05b1-3334-9ad4-bb8a07f34e93.png)