Reputation: 7317
When writing XML-compliant JSP, it is difficult to generate different HTML tags according to the input (e.g. when outputting the different tags in a <table>
).
The standard solution is to use if
or choose
tags, but sharing code inside the HTML tag becomes a problem. E.g.
<c:choose>
<c:when test="${i.tag = 'th'}><th> <!-- 100 lines of code --> </th></c:when>
<c:when test="${i.tag = 'td'}><td> <!-- 100 lines of code duplicated?! --> </td></c:when>
</c:choose>
XSLT offers an <xsl:element>
tag which allows you to build a tag and its attributes with standard XML syntax. Is there such a tag in any tag library in JSP?
Upvotes: 1
Views: 251
Reputation: 51711
Shouldn't you be doing this like?
<c:choose>
<c:when test="${i.tag = 'th'}"><th></c:when>
<c:when test="${i.tag = 'td'}"><td></c:when>
</c:choose>
<!-- 100 lines of code -->
<c:choose>
<c:when test="${i.tag = 'th'}"></th></c:when>
<c:when test="${i.tag = 'td'}"></td></c:when>
</c:choose>
<c:choose>
<c:when test="${i.tag = 'th'}">
<th>
<my:customTag anyAttributes="th-related-values-if-any" ... />
</th>
</c:when>
<c:when test="${i.tag = 'td'}">
<td>
<my:customTag anyAttributes="td-related-values-if-any" ... />
</td>
</c:when>
</c:choose>
<c:choose>
<c:when test="${i.tag = 'th'}"><c:out value="<th>%" /></c:when>
<c:when test="${i.tag = 'td'}"><c:out value="<td>%" /></c:when>
</c:choose>
<!-- 100 lines of code -->
<c:choose>
<c:when test="${i.tag = 'th'}"><c:out value="</th>%" /></c:when>
<c:when test="${i.tag = 'td'}"><c:out value="</td>%" /></c:when>
</c:choose>
Upvotes: 1
Reputation: 6344
You could create a seperate JSP containing your "100 lines of code" and include it.
Replace your <!-- 100 lines of code -->
with:
<jsp:include page="hundredLines.jsp">
<jsp:param name="beanParam" value="beanValue"/>
</jsp:include>
And in your hundredLines.jsp
:
Bean can be used like ${beanParam}
Upvotes: 1
Reputation: 8227
No. JSP requires knowing the tags when it builds its trees. That makes the operation of JSP more robust
However, you can address the duplicated code by factoring it into a separate JSP file and including it, depending on the implementation of JSP you are using.
Alternatively, you can create a JSP tag that holds the 100 lines of code. It is probably not worth while to do this.
Finally, you could, instead of using th
and td
, use styles on td
to make td
look like th
. That would make the element look like
<td style="${i.tag == 'th' ? '' : 'font-style: bold; text-align: center;'}">
100 lines of code
</td>
I know I don't have the style quite right, but you could use styleClass
instead and play with it in your CSS.
Upvotes: 0