Thursday, October 16, 2014

Iterate a Map in JSP using JSTL

Let's say we have a bean named 'CartViewBean'.

This bean has a map property named 'productMap'. This product map has the product code as the map's key and the product name as the map's value.

We will create a <select> element in our jsp and use the key-value pairs in the productMap to create the <option> tags for the <select> element.

The productMap's key will be the value and the productMap's value will be the text display of the <option> tag. So the productMap's value will be the one shown on the drop down display of the <select> statement.

You will need to create a reference to your Java bean in your JSP using the <bean:define> tag. In this example, we create a reference to the Java bean with the id 'cartVB'.

Then you will need to set a reference for the bean's map property 'cartVB.productMap' to a JSTL variable 'productMap'.

You can then iterate thru the map's elements using the  <c:forEach>  JSTL tag . You may also use the <c:remove> tag to clear and initialize the JSTL variable but it is optional.

<bean:define id="cartVB" name="cartViewBean" type="com.mycompany.view.CartViewBean"/>

<c:remove var="productMap"/>
<c:set var="productMap" value="${cartVB.productMap}" />
<select>
   <c:forEach var="product" items="${productMap}">
     <option value="<c:out value="${product.key}" />"> <c:out value="${product.value}" /> </option> 
   </c:forEach>
</select>