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.
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.