在JSTL中编写自定义函数 [英] Writing Custom Functions in JSTL

查看:117
本文介绍了在JSTL中编写自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jstl C:forEach 在jsp中打印表格。我验证它就好,

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.

是否有方法通过传递参数来重用jstl代码,就像我们为 Java 中的方法所做的那样(写入一个类并在需要的地方访问它)?

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?

推荐答案

可以定义您自己的自定义JSP标签。使用JSP 2.0,您可以使用 JSP标签文件,它们的语法非常类似于JSP页面。

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.

WE中创建一个子目录B-INF 目录: / WEB-INF / tags / mytaglib

目录中,创建一个文件 displayVarName.tag

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>

现在您可以导入您的标记并使用它在 JSP 页面中使用:

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} />

这篇关于在JSTL中编写自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆