实现下拉内容从数据库中动态读取--->Struts标签:和LabelValueBean的使用

首先,数据库中有两张表-->商品表(product)和商品类别表(category),商品跟商品类别为多对一关系,商品表中的外键categoryId引用了商品类别表中的主键categoryId,商品表中的其它字段-->商品名称(productName),商品类别表中的其它字段-->商品类别名称(categoryName)

    现在假如在页面上要添加一件商品,从一下拉框中为该商品选择类别, 而商品类别下拉框中的内容是在加载该商品添加页面时从数据库中读取的,如何实现呢?

    页面上商品类别下拉框代码如下:

< html:select property ="categoryId" styleClass ="input_text" >
       
< html:options property ="value" labelProperty ="label" collection ="categoryOptions" />
</ html:select >

与此JSP页面对应的ActionForm中的reset()方法中的相关代码如下:

public void reset(ActionMapping mapping, HttpServletRequest request) ... {
    
//从数据库的category表中读取数据设置商品类型下拉列表
     ArrayList categoryOptions=new ArrayList();
     Category category
= null;
     ICategoryService categoryService
=CategoryServiceBD.getCategoryService();
     List list
=categoryService.queryAll();
     Iterator i
=list.iterator();
    
while(i.hasNext())...{
           category
=(Category )i.next();
      //      import org.apache.struts.util.LabelValueBean;
           LabelValueBean option
=new LabelValueBean(category .getCategory Name(),category .getCategoryId().toString());
           categoryOptions.add(option);
                      }

     request.setAttribute(
"categoryOptions", categoryOptions);
}

注: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>这样就好避免出现空的错误

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值