How to display a different kind of JSP for different types of objects

Assuming I have a list of Animal (s) with standard polymorphic behavior like Cat (s) and Dog (s).

What is the best approach to display a different JSP view for each of the list?

<c:forEach var='animal' items='${animals}'> //show a different template per animal type </c:forEach> 

Honestly, having #toJSP for every bean is something I would not consider for obvious reasons.

I am tempted to use

 public interface Template{ public String render() } 

with every Animal passed in the constructor, however, I'm not sure where these objects should be created. I assume this can be done inside the JSP at <%%>, but I hesitate to use this notation for any reason.

+4
source share
4 answers

So, I ended up using the “packages” available for i18n in the JSP as follows.

 <fmt:message var="template" key="${animal.class.name}" /> 

with template.properties file

 foo.bar.Animal = animal.jsp foo.bar.Cat = cat.jsp foo.bar.Dog = dog.jsp 

So, the final solution will look like this:

 <c:forEach var='animal' items='${animals}'> <span> <c:set var="animal" scope="request" value="${animal}"/> <fmt:message var="template" key="${animal.class.name}" /> <jsp:include page="${template}" /> </span> </c:forEach> 

With template files that look like

 Hello animal ${animal}! Hello cat ${animal}! Hello dog ${animal}! 
+1
source

You can use a special tag that takes the current animal as an attribute and uses it to determine the correct representation

+1
source

Unfortunately, inheritance and polymorphism do not work very well in jsps.

The easiest and most convenient solution - just do a lot

 <c:choose> <c:when test="${animal.type == 'Cat'}"> <my:renderCat cat="${animal}"/> </c:when> <c:when test="${animal.type == 'Dog'}"> <my:renderDog Dog="${animal}"/> </c:when> ... </c:choose> 

and have tag files (e.g. renderDog.tag, renderCat.tag) that take each particular animal as an attribute and call them. at least it supports dispatching, and the rendering is split.

+1
source

Declare an abstract method for Animal that returns a string called getMyJspPage ().

Cats and dogs can then return a link to another jsp page or jsp snippet that you can include.

0
source

All Articles