How to get value of bean property when property name itself is a dynamic variable

一曲冷凌霜 提交于 2019-11-26 07:49:46

问题


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.


回答1:


If you want to use dynamic property names, use the brace notation.

<c:forEach items="${items}" var="item">
    ${item[propertyName]}
</c:forEach>


来源:https://stackoverflow.com/questions/3402052/how-to-get-value-of-bean-property-when-property-name-itself-is-a-dynamic-variabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!