Reputation: 8187
I am using jstl C:forEach
to print the table in the jsp. I validate it like ,
<c:choose>
<c:when test="${varName eq condition}">
<c:out value="${fn:substring(varName, 0, 3)}
</c:when>
<c:otherwise>
${varName}
</c:otherwise>
</c:choose>
so this prints the result as required ,and i have the scenario to use the same for other fields in the same page and also in other pages.
Is there way to reuse the jstl codes by passing the parameter to it . Something as we do for the methods in Java
(write in a class and access it wherever needed) ?
Thanks in advance for your valuble answers and comments?
Upvotes: 7
Views: 8260
Reputation: 9336
You can define your own custom JSP tags. With JSP 2.0, you can use JSP tag files, which have a syntax very similar to the JSP pages.
Create a subdirectory in the WEB-INF
directory: /WEB-INF/tags/mytaglib
In this directory, create a file displayVarName.tag
:
<%@ tag body-content="empty" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ attribute name="varName" rtexprvalue="true" required="true" type="java.lang.String" description="Description of varName" %>
<%@ attribute name="condition" rtexprvalue="true" required="true" type="java.lang.String" description="Description of condition" %>
<c:choose>
<c:when test="${varName eq condition}">
<c:out value="${fn:substring(varName, 0, 3)}
</c:when>
<c:otherwise>
${varName}
</c:otherwise>
</c:choose>
Now you can import your tag and use it in your JSP
page using:
<%@taglib prefix="mytaglib" tagdir="/WEB-INF/tags/mytaglib"%>
<mytaglib:displayVarName varName=${varName} condition=${condition} />
Upvotes: 5