struts中html:options的使用

<html:options>

html:options was born to use data in an ArrayList. Do NOT use a Vector, because it is Synchronized and will cause problems if more than one person uses your app at a time.

Given that you have a list of products with their product ID, make a drop-down that returns the product ID. First you set up your data in your controller:

ArrayList prod = new ArrayList();
prod.add( new org.apache.struts.util.LabelValueBean( "Widget", "20" ) );
prod.add( new org.apache.struts.util.LabelValueBean( "Sprocket", "29-2a" ) );
prod.add( new org.apache.struts.util.LabelValueBean( "Cog", "29s" ) );
prod.add( new org.apache.struts.util.LabelValueBean( "Dunsel", "943" ) );

LabelValueBean takes the first String argument as the displayed name and the second as the value returned. We’ll see more about this in a bit.

Now that you have prod set up, you pass that as a session or request bean to the JSP.

request.setAttribute( Constants.PRODUCT_KEY, prod );

(the Constants.PRODUCT_KEY is set to our bean name: "products"; we use this to centralize bean name management)

To use the data in the JSP, add the following code:

  <html:select property="product_id" styleClass="prodselect" >
    <html:options collection="products" property="value" labelProperty="label" />
  </html:select>

Notes: product_id is the variable the JSP will set to the product ID value of the product selected by the user. products is the name of the bean (it must match what is in Contants.PRODUCT_KEY -- we probably could've said

... collection="<%= Constants.PRODUCT_KEY %>" ...

in place of hard-coding the name. The choice is up to you.

property="value" and labelProperty="label" are automatically set by org.apache.struts.util.LabelValueBean, so only use the values shown here.

The resulting HTML will look something like:

<select name="product_id" size="1">
<option value="20">Widget</option>
<option value="29-2a">Sprocket</option>
<option value="29s">Cog</option>
<option value="943">Dunsel</option>
</select>

Which renders as

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值