View all fields / properties of bean in JSP / JSTL
37,546
Solution 1
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>${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><% object.getName() %></em></h2>
<ul>
<c:forEach var="method" items="${object['class'].declaredMethods}">
<c:catch><li>${method.name}</li></c:catch>
</c:forEach>
</ul>
</c:if>
Solution 2
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: ${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>: ${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>
Author by
Toby
Updated on September 07, 2020Comments
-
Toby over 3 years
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>
-
Ianthe the Duke of Nukem about 8 yearsDankeschön für das