Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...