Jsp自訂Tag

來源:互聯網
上載者:User

標籤:

自訂Tag標籤,繼承SimpleTagSupport實現,位於javax.servlet.jsp.tagext

Maven dependency

<dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.1</version></dependency>

實際情境很少使用,主要學習java實現自訂標籤的思想

 

執行自訂標籤中內容代碼位於doTag方法內

而SimpleTageSupport類具有一些方法:

JspContext getJspContext()

   JspContext通過方法 getOut(),獲得JspWriter。JspWriter的print()方法可以將內容寫入到Jsp頁面中。

   JspContext通過getAttribute() setAttribute()設定擷取JspTag範圍或其他範圍的Attribute值。

 

JspTag getParent(),可以通過該方法獲得父標籤內容。通過擷取父標籤和子標籤內容可以組合出各種複雜功能的Jsp Tag。如If While 的分支選擇Tag。

 

JspFragment getJspBody(), 獲得標籤體。JspFragment.invoke(Writer writer), 將標籤內容寫入Writer。如果writer為null, 標籤體內容如普通jsp頁面輸出。

 

需先定義tld檔案

<?xml version="1.0" encoding="GBK" ?>  <taglib xmlns="http://java.sun.com/xml/ns/j2ee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"  version="2.0">  <tlib-version>1.0</tlib-version>  <short-name>mytaglib</short-name>  <uri>http://domain/mytaglib</uri>  <tag>      <name>helloWorld</name>      <tag-class>mypackage.HelloWorldTag</tag-class>      <body-content>empty</body-content>      <attribute>          <name>content</name>          <required>true</required>          <fragment>true</fragment>      </attribute>  </tag>  <tag>      <name>iterator</name>      <tag-class>mypackage.iteratorTag</tag-class>      <body-content>scriptless</body-content>      <attribute>          <name>collection</name>          <required>true</required>          <fragment>true</fragment>      </attribute>      <attribute>          <name>item</name>          <required>true</required>          <fragment>true</fragment>      </attribute>  </tag>  

是用前使用TagLib指令匯入

<%@ taglib uri="WEB-INF/tlds/mytag.tld" prefix="mytag" %>

 

 

 

Jsp自訂Tag

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.