View all fields / properties of bean in JSP / JSTL

Toby picture Toby · Apr 30, 2013 · Viewed 35.4k times · Source

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>

Answer

Toby picture Toby · Jul 4, 2014

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>