首先,数据库中有两张表-->商品表(product)和商品类别表(category),商品跟商品类别为多对一关系,商品表中的外键categoryId引用了商品类别表中的主键categoryId,商品表中的其它字段-->商品名称(productName),商品类别表中的其它字段-->商品类别名称(categoryName)
现在假如在页面上要添加一件商品,从一下拉框中为该商品选择类别, 而商品类别下拉框中的内容是在加载该商品添加页面时从数据库中读取的,如何实现呢?
页面上商品类别下拉框代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
与此JSP页面对应的ActionForm中的reset()方法中的相关代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/0196c3df5ea9e936f21e9932cca91014.gif)
注:LabelValueBean的构造方法public LabelValueBean(String label, String value),需要两个参数,这两个参数与页面的下拉框标签<html:options property="value" labelProperty="label" collection="categoryOptions"/>
中的两个属性对应,label是显示给用户看到的文本,value是保存到数据库中的值。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1705123
最后一定要注意html:select property="categoryId" 的值,一定要和Action Form的formbean的值对应,要不然会出现说找不到No getter method available for property **** for bean under name org.apache.struts.taglib.html.BEAN
还有,最好在<html:options property="value" labelProperty="label" collection="categoryOptions"/>
加入logic标签,判断是否为空
<logic:notEmpty name="categoryId">
<html:options property="value" labelProperty="label" collection="categoryOptions"/>
</logic:notEmpty>这样就好避免出现空的错误