自定義標籤的接口關係圖html
1)建立標籤的處理類 建立的標籤處理類要繼承javax.servlet.jsp.tagext.TagSupport 類 或 javax.servlet.jsp.tagext.BodyTagSupport 類, 並重寫 兩個重要的方法 doStartTag(),doEndTag()java
2)建立標籤庫描述文件(格式 .tld 其實就是一個xml文檔), 這個文件要放在WEB-INF目錄下web
3)在jsp文件中引入標籤庫,而後插入標籤,例如 Servlet容器編譯jsp文件時,若是遇到自定義標籤就會調用這個標籤的處理類jsp
編寫tag類ide
package com.lious.tag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; public class MyTag extends TagSupport{ @Override public int doStartTag() throws JspException { try { this.pageContext.getOut().write("hello"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { try { this.pageContext.getOut().write("i'm coming---"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SKIP_PAGE; } }
編寫tld文件this
<?xml version="1.0" encoding="UTF-8" ?>
<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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>hello</short-name> <uri>http://java.sun.com/jsp/jstl/mytag</uri> <tag> <name>hello</name> <tag-class>com.lious.tag.MyTag</tag-class> <body-content>JSP</body-content> </tag> </taglib>
jsp頁面spa
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/mytag" prefix="hello" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <hello:hello>北京天安門,</hello:hello> <hr> <p>其實我還好</p> </body> </html>
簡單的demo,運行效果code