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?
Thymeleaf, JSF, AngularJS, JavaScript, and guava are the most popular alternatives and competitors to JSTL.
JSP lets you even define your own tags (you must write the code that actually implement the logic of those tags in Java). JSTL is just a standard tag library provided by Sun (well, now Oracle) to carry out common tasks (such as looping, formatting, etc.).
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates the core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags.
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} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With