I found out something cool about JSTL’s expression language today that I didn’t expect at all – like a real scripting language, EL allows one to access an object’s fields not only like object.fieldname (which wouldn’t be changeable at runtime) but also as object[“fieldname”] and by extension with any string variable as an argument. Wow! I don’t remember seeing any examples of this in the wild – somehow i stumbled upon it in the bowels of a unified expression language tutorial.
This came in handy DRYing out some JSP code today that differed only in the fields accessed on the same kind of objects – I thought immediately, if only I had a scripting language this could all go away! Then I thought about the long and winding road one might take to do that in java, involving reflection and/or long if/else blocks. I was pleasantly surprised to find out JSTL can do that. Phew.
Here’s a poor example:
What you’d have to do w/o this capability
${object.dog} ${object.cat}
and with
<c :set var="fieldName" value="dog" /> ${object[fieldName]}
i told you it was a bad example.
Brian,
thanks for this post, I was looking for this one. It has gone unnoticed in my 3 years of JSTL usage…
thanks
Sathiya