Monday, December 24, 2007

Using HashMap with Struts <html:options> tag

One of the most common tasks in writing HTML forms is populating drop-down lists with values. In Struts, this can be done by using the <html:option> tag. In some cases, you may want to populate the drop-down with values retrieved from the database. Once retrieved from the database, you may want to store the value/label pairs in a HashMap. What many don't know is that you can actually use the <html:options> tag to generate the list based on a HashMap.

In the following scenario, these assumptions are made.
  1. An attribute named "aisles" is stored as an attribute in the ServletContext.
  2. "aisles" is a HashMap. The key is the aisle Id, while the value is the aisle's description. For example, the key = "1", and the value = "Dairy".
Now, in the JSP, to create a drop-down list populated with the key and value pairs in the "aisles" HashMap, all you need to do is write:

<html:select property="aisleId">
<html:options collection="aisles" property="key" labelProperty="value" />
</html:select>


This will generate HTML similar to the following:

<select name="aisleId">
<option value="1">Dairy</option>
<option value="2">Frozen Foods</option>
<option value="3">Beverages</option>
<option value="4">Breakfast Foods</option>
<option value="5">Snacks, Cookies, &amp; Candy</option>
<option value="6">Grains &amp; Pastas</option>
<option value="7">Soups &amp; Canned Goods</option>
<option value="8">Baking Goods</option>
<option value="9">Condiments</option>
</select>