Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom rendering in JSP based on type of class without instanceof

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?

like image 429
Nick Sonneveld Avatar asked Mar 29 '09 14:03

Nick Sonneveld


1 Answers

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>
like image 158
Maurice Perry Avatar answered Sep 23 '22 09:09

Maurice Perry