Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View all fields / properties of bean in JSP / JSTL

I have a bean, ${product}. I would like to view all of the available fields / properties of this bean. So for instance, ${product.price}, ${product.name}, ${product.attributes.colour} etc.

Is it possible to dynamically print out all names and values of these properties in JSP, using JSTL/EL?

Something like:

<c:forEach items="${product}" var="p">  
    ${p.key} - ${p.value}
</c:forEach>
like image 578
Toby Avatar asked Apr 30 '13 14:04

Toby


2 Answers

Replace object with the bean to determine.

<c:set var="object" value="${product}" />

Display all declared fields and their values.

<c:if test="${not empty object['class'].declaredFields}">
    <h2>Declared fields <em>&dollar;{object.name}</em></h2>
    <ul>
        <c:forEach var="field" items="${object['class'].declaredFields}">
            <c:catch><li><span style="font-weight: bold">
                ${field.name}: </span>${object[field.name]}</li>
            </c:catch>
        </c:forEach>
    </ul>
</c:if>

Display all declared methods.

<c:if test="${not empty object['class'].declaredMethods}">
    <h2>Declared methods<em>&lt;% object.getName() %&gt;</em></h2>
    <ul>
        <c:forEach var="method" items="${object['class'].declaredMethods}">
            <c:catch><li>${method.name}</li></c:catch>
        </c:forEach>
    </ul>
</c:if>
like image 154
Toby Avatar answered Oct 21 '22 11:10

Toby


Ready to use version of @Toby's answer

<p class="TODO <your name> PRINT OBJECT PROPERTIES">
    <c:set var="object" value="${<your object here>}" />
    <h2><b>Object:&nbsp; ${object.class} </b></h2>
    <h3><b>Declared fields</b></h3>
    <c:if test="${!empty object.class.declaredFields}">
        <ul>
            <c:forEach var="attr" items="${object.class.declaredFields}">
                <c:catch><li><b>${attr.name}</b>:&nbsp; ${object[attr.name]}</li></c:catch>
            </c:forEach>
        </ul>
    </c:if>
    <c:if test="${empty object.class.declaredFields}">No declared fields</c:if>
    <h3><b>Declared methods</b></h3>
    <c:if test="${!empty object.class.declaredMethods}">
        <ul>
            <c:forEach var="attr" items="${object.class.declaredMethods}">
                <c:catch><li><b>${attr.name}</b>(...)</li></c:catch>
            </c:forEach>
        </ul>
    </c:if>
    <c:if test="${empty object.class.declaredMethods}">No declared methods</c:if>
</p>
like image 2
honzajde Avatar answered Oct 21 '22 09:10

honzajde