How would you properly render a list of objects in jsp with differing types? Say, for example, I have to render these different objects in a specified order.
One way could be to use a common type variable or instanceof but that means having a big switch/if statement to manage them all:
<c:forEach var="o" items="${bigListofObjects}" >
<c:choose>
<c:when test='${o.type=="simple"}' >
<!-- render simple -->
</c:when>
<c:when test='${o.type=="complex"}' >
<!-- render complex -->
</c:when>
<!-- etc etc ... -->
</c:choose>
</c:forEach>
I could add a render() method to each class but then that means mixing the view with the rest of the code.
What happens if I want to render another type later on? Is there something I could do with custom jsp tags?
You could include another jsp that would do the correct rendering for a given type. for instance:
<c:forEach var="o" items="${bigListofObjects}" >
<c:import url="render-${o.type}.jsp"/>
</c:forEach>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With