JSTL自定義標簽


當JSTL標簽庫已經無法滿足我們的需求時候,就需要自己開發自定義標簽,來滿足我們的需求,自定義標簽實際上是一個普通的java類,繼承SimpleTagSupport類。

做類。派生自SimpleTagSupport,重寫doTag()方法。getJspBody(),getJspContext(),invoke(null);

package com.itnba.maya.zidingyi;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.*;

public class Zidingyijstl extends SimpleTagSupport {
    private String a="p";    

    public void setA(String a) {
        this.a = a;
    }
    private int b;
    public void setB(int b){
        this.b=b;
    }

    public void doTag() throws JspException, IOException {    //重寫doTage()方法
        JspFragment frag=this.getJspBody();
        this.getJspContext().getOut().write("<"+a+">");
        for(int i=0;i<b;i++){
        frag.invoke(null);
        }
        this.getJspContext().getOut().write("</"+a+">");
    
    }

}

在web項目的WEB-INF目錄下建立tld文件(myjstl.tld),這個tld文件為標簽庫的聲明文件,並配置好相應的信息。(可以參考核心標簽庫的tld文件)

 

<?xml version="1.0" encoding="UTF-8"?>

<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>自定義的一些標簽</description>
  <display-name>自定義標簽</display-name>
  <tlib-version>1.0</tlib-version>
  <short-name>m</short-name>
  <uri>http://www.itnba.com/maya/myjstl</uri>
  
  <tag>
    <description>
          描述
    </description>
    <name>show</name>   <!-- 標簽名 -->
    <tag-class>com.itnba.maya.zidingyi.Zidingyijstl</tag-class>  <!-- 唯一標識 -->
    <body-content>scriptless</body-content>   <!--  標簽里不可寫腳本<%%>-->
    
      <!--  添加屬性-->
     <attribute>
        <description>
        這是自定義標簽的描述信息,可以在MyEclipse中有提示
        </description>
        <name>a</name>          <!--  屬性的名字,要跟方法名要對應的-->
        <required>false</required>   <!--是否必填-->
        <rtexprvalue>false</rtexprvalue>  <!--標簽里可不可以用EL表達式-->
    </attribute>
    
    <!--再寫一個方法-->
    <attribute>
        <description>
        這是自定義標簽的描述信息,可以在MyEclipse中有提示.
        </description>
        <name>b</name>                 <!--  屬性的名字,要跟方法名要對應的-->
        <required>true</required>     <!--是否必填-->
        <rtexprvalue>false</rtexprvalue>   <!--標簽里可不可以用EL表達式-->
    </attribute>
  </tag>
  
</taglib>

 jsp頁面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="m" uri="http://www.itnba.com/maya/myjstl" %>    <%--配置 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<m:show b="2" a="h2">
haha
</m:show>
</body>
</html>

顯示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM