Skip to main content

Accessing & iterating over a Java Map in a JSP page with JSTL

When you are coding JSP pages using JSTL one thing you use a lot is the <c:foreach> tag. This tag a great for iterating over Lists or Sets but what do you do when you want to display the contents of a Map?

Firstly you need to decide how you are going to use the Map. Do you want to access a 'value' stored within the Map based on a known key or iterate over the Map displaying both key and value?

Access a Map based on a 'key'

This one is pretty straight forward you just need to know the JSTL syntax:
${aMapFullOfKeysAndValues[yourKnownKey]}
Two key points:
  • The key is an existing JSTL variable or a quoted string
  • You use square brackets at the end of the Map name
Iterate over a Map pulling out the 'key' & 'value'

This is a little more complex, note the name of the variable that is filled on each pass through the Map ('entry'):

    ${entry.key} - ${entry.value}
Four key points:
  • The name of the Map is placed as the 'items' attribute of the forEach
  • To access the 'key' object use ${entry.key}
  • To access the 'value' object use ${entry.value}
  • If either the key or value is a complex object, simply walk into it: ${entry.value.surname}
Hopefully that has demystified it a little, please post a comment if you found this post useful or I've missed something out!

Comments

aakashi said…
its nice tutorial kind a post,i liked so much,coz its so useful.