Search code examples
javastruts-1

Iterating over hashmap in JSP in struts application


I have a HashMap object that I am getting on a JSP page.

HashMap<Integer,Gift_product> gift_hm = new HashMap<Integer,Gift_product>();
gift_hm.put(17,new Gift_product("doll",67));

Now I need to iterate this and display content on JSP. The Gift_product class contains two fields: name and price.

JSP output should be

serial no.           product name     price
17                    Doll            67

How can I achieve it?


Solution

  • Check out the struts <logic:iterate> tag. When iterating over a HashMap, each entry is a java.util.Map.Entry, to get the key (in this example the serial number) and value (the Gift_product object) out use the key and value properties like this:

    First set the HashSet as an attribute in your action class e.g. request.setAttribute("gift_hm", gift_hm); and then in the jsp:

    <logic:iterate id="mapEntry" name="gift_hm">
      <bean:define id="gift" name="mapEntry" property="value">
      <tr>
        <td><bean:write name="mapEntry" property="key"></td>
        <td><bean:write name="gift" property="productName"></td>
        <td><bean:write name="gift" property="price"></td>
      </tr>
    </logic:iterate>