qiyadeng

专注于Java示例及教程
posts - 84, comments - 152, trackbacks - 0, articles - 34

动态的级联下拉框解决方案(二)

Posted on 2005-12-26 17:16 qiyadeng 阅读(989) 评论(0)  编辑  收藏

 这也是个开源的标签库^_^,因为老外总是很专业些写了很多好东西,可是我基本上是和他们相反,即没有时间也比较懒得。Struts-layout是一个用来扩充Struts的html标签的作用的,我以前写过(blog里)了怎么安装使用的,这里就不说了。
layoutselect.bmp
1.这次我们先看JSP的结构:


  <head>
    <script src="/WebSample/config/javascript.js"></script>
  </head>
 
  <body>
  <html:form action="/country.do">
    <layout:select key="Country" property="countryId">    
  <layout:option value=""/>
  <layout:options collection="countries" property="countryId" labelProperty="name" sourceOf="cityId"/>
 </layout:select>
 
 <layout:select key="City" property="cityId">
  <layout:optionsDependent collection="cities" property="cityId" labelProperty="cityName" dependsFrom="countryId"/>
 </layout:select>
 <html:submit /><html:reset />
  </html:form> 
  </body>
两个select,其中第二个是<layout:optionsDependent/>它的dependsFrom的属性需要和上面的那个select的property一致。countries是在request域的一个collection,而cities是countries的一个属性,但是类型也是collection。
2.Action:你需要Action来初始化countries,

 public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) { 
  List countries = new ArrayList();
  for(int i = 0 ;i< 10 ;i++){
   Country c = new Country();
   c.setCountryId(new Integer(i));
   c.setName("country"+i);
   for(int j = 0;j< 5 ;j++){
    c.addCity("city"+i+j,new Integer(i*10+j));
   }
   countries.add(c);
  }
  request.setAttribute("countries",countries);
  return mapping.findForward("success");
 }
这样你基本上就好了,够简单吧!下面还有两个类的结构就是Country类和CityBean类:
Country类:3个如下属性,外加Setter/Getter方法。
 private String name;
 private List cities = new ArrayList();
 private Integer countryId;
CityBean类:2个如下属性,外加Setter/Getter方法。
 private Integer cityId;
 private String cityName;
这些东西你当然还可以和数据库结合起来使用,或是和XML文件结合起来使用。基本上一个应用最要需要考虑好
类似Country类这个结构就可以了。

这个标签的方法是把所有的数据都会写入到html文件中,并写入相应的JavaScript,你可以查看源码。


<script>var countries = new Array();
countries[0] = new Object();
countries[0].value = "0";
countries[0].cities = new Array();
countries[0].cities[0] = new Object();
countries[0].cities[0].value = "0";
countries[0].cities[0].label = "city00";
countries[0].cities[1] = new Object();
countries[0].cities[1].value = "1";
countries[0].cities[1].label = "city01";
countries[0].cities[2] = new Object();
countries[0].cities[2].value = "2";
countries[0].cities[2].label = "city02";
countries[0].cities[3] = new Object();
countries[0].cities[3].value = "3";
countries[0].cities[3].label = "city03";
countries[0].cities[4] = new Object();
countries[0].cities[4].value = "4";
countries[0].cities[4].label = "city04"
.....
</script>

个人总结,水平有限。主要是最近在论坛里看到不少关于这方面的问题,然后有没有最后的答案,所以借助开源标签可以做到通用性,希望对您有所帮助。


只有注册用户登录后才能发表评论。


网站导航: