首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

JSP 自定義標籤完整開發教程:從簡單標籤到屬性、迴圈與表達式支援

     編輯:Java 綜合教學

JSP 自定義標籤完整開發教程:從簡單標籤到屬性、迴圈與表達式支援

建立簡單標籤處理器三步驟

  1. 編寫標籤處理器 (Java 類)
  2. 在 TLD 檔案描述標籤
  3. 在 JSP 引用標籤

詳細步驟

Step 1:繼承 SimpleTagSupport

package foo;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class SimpleTagTest1 extends SimpleTagSupport {
    // 標籤處理代碼
}

Step 2:實作 doTag() 方法

public void doTag() throws JspException, IOException {
    getJspContext().getOut().print("This is xxxxxx");
}

Step 3:建立 TLD (Tag Library Descriptor)

<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib xmlns="https://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
    <tlib-version>1.2</tlib-version>
    <uri>simpleTags</uri>
    <tag>
        <name>simple1</name>
        <description>xxxxxxxx</description>
        <tag-class>foo.SimpleTagTest1</tag-class>
        <body-content>empty</body-content>
    </tag>
</taglib>

Step 4:部署

TLD 放 WEB-INF,標籤處理器放 WEB-INF/classes (遵循包結構)。

Step 5:JSP 使用

<%@ taglib prefix="myTags" uri="simpleTags" %>
<html><body>
<myTags:simple1 />
</body></html>

URI 需與 TLD 中 uri 一致。

常見進階情況

情況一:有主體內容的標籤

<myTags:simple2> This is the body </myTags:simple2>

doTag() 加入 getJspBody().invoke(null);,TLD body-content 改為 scriptless。

情況二:主體使用 EL 表達式

<myTags:simple3> Message is : ${message} </myTags:simple3>

doTag() 設定屬性:getJspContext().setAttribute("message","wear sunscreen"); getJspBody().invoke(null);

情況三:迴圈輸出集合資料

<table>
<myTags:simple3>
<tr><td>${movie}</td></tr>
</myTags:simple3>
</table>

doTag() 迴圈設定屬性並多次 invoke:

String[] movies = {"Monsoon Wedding", "Saved!", "..."};
public void doTag() throws JspException, IOException {
    for(int i=0; i

情況四:帶屬性的簡單標籤

<myTags:simple5 movieList="${movieCollection}">
<tr><td>${movie.name}</td><td>${movie.genre}</td></tr>
</myTags:simple5>

TLD 加入 attribute 定義,標籤處理器加入對應屬性與 setter。

補充:body-content 四種參數

  1. empty:標籤主體為空
  2. scriptless:無腳本元素,可有模板文字、EL、自定義/標準動作
  3. tagdependent:主體視為純文字,不計算 EL、不觸發標籤/動作
  4. JSP:JSP 允許的內容皆可放入

轉自:https://www.cnblogs.com/elaron/archive/2012/10/10/2717797.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved