How to write a JSP which renders a list of JSP fragments, without IF switching code
I have a JSP which composes a List of Objects, then renders JSP fragments depending on the Class of each of the objects in the List. At the moment, this is done with a huge chain of if statements inside the 'parent' JSP:
if( bean.getFilterChildByType( Level.class ) != null )
{
%> <jsp:include page="filters/level.jsp"/> <%
}
if( bean.getFilterChildByType( Sources.class ) != null )
{
%> <jsp:include page="filters/sources.jsp"/> <%
}
...
So, my question is, in JSP (Tomcat) is it possible to achieve this same functionality without an if chain, just by itera开发者_高级运维ting the Objects in the list and perhaps taking advantage of the naming convention "Class name".jsp ? I've played with:
<%@ include file="filename" %>
but this doesn't seem to allow variables in the file-name either.
Something like this should work
<jsp:include page="filters/<%=filename%>.jsp"/>
Resolve the appropriate jsp to be included (based on bean.getFilterChildByType
) at the controller side and then just pass the name of the jsp to the container jsp. Now this can be easily included.
This is a tough one!
If the included jsp files (level.jsp, source.jsp, etc) are not too complex, what about shifting the HTML from those files over to a function call of the objects you are calling bean.getFilterChildByType(...) on?
That way, instead of a large if/else tree, you could then just call:
String html = bean.getHtmlForType();
...would likely work out much cleaner in a loop too.
精彩评论