Tech-Freaks.in

Technically Driven To Perfection!

  • Increase font size
  • Default font size
  • Decrease font size
Home Rapid Code Iterating a Map using JSTL/EL

Iterating a Map using JSTL/EL

E-mail Print
Normally, we iterate through a list (like ArrayList, LinkedList etc) in JSP. For map (HashMap, TreeMap etc), we would generally be picking up 'value' based on the 'key'.

However, there are situations in which we would like to iterate all the elements of a map and display its key and value. For example, display a list of attribute name and value of a guitar! Each attribute name of the guitar represented as a key and the attribute value as a value. The key value pair would be something like this ('Type', 'Electric'), ('Brand', 'Gibson') etc.
 
  ....
  .... 
  <c:forEach var="item" items="${itemsMap}">
${item.key} -->  ${item.value} </br>
  </c:forEach>
  ....
'itemsMap' would be a type of Map which is in request scope. 

The below code is an excerpt from a servlet which adds 'itemsMap' in request scope and forwards to the JSP which iterates the Map.

public void service(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  Map map = new HashMap();
  map.put("Type", "Electric");
  map.put("Brand", "Gibson");
  map.put("Model", "Les Paul Black Beauty");
  request.setAttribute("itemsMap", map);
  
  request.getRequestDispatcher("/DisplayMap.jsp").forward(request, response);
 }


One thing to worry about while iterating this way is the ordering of elements. Ensure to use a LinkedHashMap instead of a HashMap, if the order of the elements to be displayed is important. 

(0 Votes)
Comments (2)
Correction done
2 Thursday, 01 October 2009 19:14
Tech Programmer
Bob,

Thanks for the comment. Correction is made as per your suggestion. Also, added servlet code which adds itemsMap in request scope.
correction
1 Thursday, 01 October 2009 16:11
bob
you mean 'itemsMap' would be a type of Map which is in request scope.

Add your comment

Your name:
Subject:
Comment:
Last Updated on Thursday, 01 October 2009 19:09