標籤:自訂標籤 ... extend oid 代碼 uri xtend web exce
第一步,做一個類,派生自SimpleTagSupport,“alt+/”選重寫doTag()方法。
public class TestTag extends SimpleTagSupport { private String outerTagName="p"; public void setOuterTagName(String outerTagName) { this.outerTagName = outerTagName; } private int count; public void setCount(int count) { this.count = count; } @Override public void doTag() throws JspException, IOException { JspFragment frag = this.getJspBody(); //當前產生的片段 this.getJspContext().getOut().write("<"+outerTagName+">");//添加的屬性 for(int i=0;i<count;i++){ frag.invoke(null);//產生輸出 } this.getJspContext().getOut().write("</"+outerTagName+">"); }}
第二步,配置
在WEB-INF檔案夾中建立一個XML.File檔案,副檔名更改為tld,選擇XML template,完成建立。
taglib為根項目
<taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1">
根項目下面寫對整個檔案的描述
<description>自訂jstl標籤</description> 描述
<display-name>JSTL自訂標籤</display-name> 顯示的名字
<tlib-version>1.1</tlib-version> 版本
<short-name>c</short-name> 首碼
<uri>http://www.itnba.com/maya/myjstl</uri> 唯一標識
<description>自訂jstl標籤</description> <display-name>JSTL自訂標籤</display-name> <tlib-version>1.1</tlib-version> <short-name>c</short-name> <uri>http://www.itnba.com/maya/myjstl</uri>
後面寫<tag>標籤
<name>catch</name> 引用時:後面就是這個名字
<tag-class>com.itnba.maya.myel.TestTag</tag-class> com.itnba.maya.myel是第一步做的包名 TestTag是類名
<body-content>scriptless</body-content> 不能寫指令碼,即不能寫<%%>
<required>false</required>是否必填,true是自動產生必須填,false可寫可不寫
<rtexprvalue>false</rtexprvalue>是否可以用el運算式<tag>
<tag> <description> ...描述 </description> <name>catch</name> <tag-class>com.itnba.maya.myel.TestTag</tag-class> <body-content>scriptless</body-content> <attribute> <description> 第一條屬性 </description> <name>outerTagName</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <description> 第二條屬性 </description> <name>count</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag></taglib>
第三步,現在就可以引用這個JSTL自訂的標籤了
先導一下寫好的el函數,
prefix是在${}中用的名,uri是第二步配置中的那個唯一標識
<%@ taglib prefix="c" uri="http://www.itnba.com/maya/myjstl" %>
用prefix名:<tag>中<name>,後面就可以把寫好的屬性加上
<c:catch outerTagName="h3" count="2">Hello Lee<br></c:catch>
這段代碼應該顯示三號標題,count是迴圈次數,兩次,顯示如。
自己封裝JSTL 自訂標籤