JSTL自訂標籤,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>
顯示