我正在使用 jSTL C:forEach
在 jsp 中打印表格。我像这样验证它,
<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>
所以这会根据需要打印结果,我有在同一页面和其他页面中对其他字段使用相同结果的场景。
有没有办法通过将参数传递给它来重用 jSTL 代码。就像我们为 Java
中的方法所做的那样(编写一个类并在需要的地方访问它)?
提前感谢您宝贵的回答和意见?
最佳答案
您可以定义自己的自定义 JSP 标记。使用 JSP 2.0,您可以使用 JSP tag files ,其语法与 JSP 页面非常相似。
在WEB-INF
目录下创建子目录:/WEB-INF/tags/mytaglib
在此目录中,创建一个文件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
页面中使用它:
<%@taglib prefix="mytaglib" tagdir="/WEB-INF/tags/mytaglib"%>
<mytaglib:displayVarName varName=${varName} condition=${condition} />
关于java - 在 JSTL 中编写自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27201778/