---
title: "Struts2 Map嵌套List实现"
author: "andyjames"
date: "2008-05-22T14:57:18Z"
tags: []
categories: ["企业架构"]
slug: "struts2-map-list"
draft: false
lastmod: "2008-05-22T14:57:18Z"
id: 195663
url: "https://andyjames.iteye.com/blog/195663"
---

最近一直在研究struts2,看了sturts2和博客的相关文章，学习了Struts2 Map嵌套List实现，下面是是示例演示：

要求：一个业务线对应一个目录树

![](http://hiphotos.baidu.com/vsandjava/pic/item/dff40e248f54383ad507425b.jpg)

过程:

1.页面前一个Action中实现ServletRequestAware接口

2.在Action中将serviceTypesCategories 放入request中

private Map&lt;String, List&lt;Category&gt;&gt; serviceTypesCategories = new HashMap&lt;String, List&lt;Category&gt;&gt;();

request.setAttribute("serviceTypesCategories", serviceTypesCategories);

3.JSP页面代码

&lt;s:iterator value="%{serviceTypesCategories.keySet()}" id="serviceTypeString" &gt;  
&lt;s:set name="serviceTypeRequest" scope="request" value="#serviceTypeString"/&gt;  
       &lt;s:text name="preferential\_servicestype"/&gt;:&lt;s:property value="serviceTypeString"/&gt;&lt;br&gt;  
     &lt;%  
       Map&lt;String, List&lt;Category&gt;&gt; serviceTypesCategories = (Map&lt;String, List&lt;Category&gt;&gt;) request  
           .getAttribute("serviceTypesCategories");  
       String servicetype = (String) request.getAttribute("serviceTypeRequest");  
       PreferentialCheckTreeUtil util = new PreferentialCheckTreeUtil();  
       List&lt;Category&gt; myCategories = serviceTypesCategories.get(servicetype);  
       List&lt;Category&gt; rootCategories = new ArrayList&lt;Category&gt;();

       out.println(" &lt;script language=\\"JavaScript\\"&gt;");  
       out.println("var check" + treeIndex + " = new CheckTree('check" + treeIndex + "');");  
       out.println("&lt;/script&gt;");

       out.println(" &lt;ul id=\\"tree-check" + treeIndex + "\\" class=\\"checktree\\"&gt;");

       for (Category category : myCategories) {  
         if (category.getLevel() == 1) {  
           rootCategories.add(category);  
         }  
       }  
       final PrintWriter mcpsOut = response.getWriter();  
       for (Category rootCategory : rootCategories) {  
         // out.println(rootCategory.getName());  
         //判定是否是当前层的最后一个节点  
         if (rootCategory.getId() == rootCategories.get(rootCategories.size() - 1).getId()) {  
           util.printCategoryWithCheck(rootCategory, out, true);  
         }  
         else {  
           util.printCategoryWithCheck(rootCategory, out, false);  
         }  
       }  
       out.println("&lt;/ul&gt;");  
       treeIndex++;  
     %&gt;  
&lt;/s:iterator&gt;

注意：这里使用了&lt;S:SET/&gt;标签，并且设置scope为request,如果不放入request中，会出现页面偶尔显示不出来的情况,

原因是: &lt;s:iterator value="%{serviceTypesCategories.keySet()}" id="serviceTypeString" &gt;

默将serviceTypeString放入stack context中，并非reqeust中.