How to get value of bean property when property name itself is a dynamic variable
I'm trying to write a custom JSPX tag that reads the value of a given bean property from each object in a given list, with the name of that property passed to the tag as a JSP attribute. The tag would look something like this:
<jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:jsp="http://java.sun.com/JSP/Page"
version="2.0">
<jsp:output omit-xml-declaration="yes"/>
<jsp:directive.attribute name="items" type="java.lang.Iterable"
required="true" description="The items whose properties are to be read"
rtexprvalue="true"/>
<jsp:directive.attribute name="propertyName" type="java.lang.String"
required="true" description="The name of the bean property to read"
rtexprvalue="true"/>
<c:forEach items="${items}" var="item">
<!-- This is the bit that doesn't work -->
<jsp:getProperty name="item" property="${propertyName}" />
</c:forEach>
</jsp:root>
The problem is that the property
attribute of the jsp:getProperty
tag doesn't seem to accept an expression, only a literal value. So this would work, but is no use to me (as I don't know the property name until runtime):
<jsp:getProperty name="item" property="firstName" />
The error I get is:
org.apache.jasper.JasperException: org.apache.jasper.JasperException:
PWC6054: Cannot find any information on property '${propertyName}' in
a bean of type 'com.example.FooBar'
Thanks for any help.
If you want to use dynamic property names, use the brace notation.
<c:forEach items="${items}" var="item">
${item[propertyName]}
</c:forEach>