Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Custom Functions in JSTL

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?

like image 765
Santhosh Avatar asked Nov 29 '14 11:11

Santhosh


People also ask

What is the alternative for JSTL?

Thymeleaf, JSF, AngularJS, JavaScript, and guava are the most popular alternatives and competitors to JSTL.

What is the difference between JSP and 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.).

Is JSTL a programming language?

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.


1 Answers

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} />
like image 178
obourgain Avatar answered Sep 30 '22 08:09

obourgain