JSTL自定义标签

van*_*van 12 jsp jstl jsp-tags

我如何为具有2个属性的自定义标签编写(只是一个模板),这些属性允许我使用jstl标记逻辑输出html片段(html表),可以从我的jsp调用.

这可以在不编写java类的情况下完成,这是我在所有示例中看到的.

我想要实现的是将我的JSP中重复的JSTL逻辑外部化为自定义标记,然后使用属性在运行时传递标记所需的动态值.

谢谢,

Viv*_*ath 30

不要使用scriptlet!它们是一种不好的做法,它们让业务逻辑泄漏到您的视图层.

您可以使用JSTL创建标记文件; 这很简单.是一个很好的起点.

一个例子:

mytable.tag:

<%@ attribute name="cell1" required="true" type="java.lang.String" description="Text to use in the first cell." %>
<%@ attribute name="cell2" required="false" type="java.lang.String" description="Text to use in the second cell." %>

<table>
 <tr>
  <td id = "cell1">${cell1}</td>
  <td id = "cell2">${cell2}</td>
 </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

假设你的标签在/WEB-INF/tags,你可以像这样使用它:

<%@ taglib prefix="mystuff" tagdir="/WEB-INF/tags" %>

<mystuff:mytable cell1="hello" cell2="world" />
Run Code Online (Sandbox Code Playgroud)