1、定义一个Java类,需要继承javax.servlet.jsp.tagext.TagSupport,里面有许多方法,不一一详述,自己去看看源码就知道了
package com.seeyon.jsptag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; /** * Created by yangyu on 2017/2/16. */ public class JspTag extends TagSupport{ private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } @Override public int doStartTag() throws JspException { System.out.println("tag start "+getName()); return 1; } }
2、需要在classpath下META-INF目录下创建.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>JSP Tag</description> <tlib-version>1.1</tlib-version> <short-name>myjsptag</short-name> <uri>/myjsptag</uri> <tag> <name>mytag</name> <tag-class>com.seeyon.jsptag.JspTag</tag-class> <body-content>JSP</body-content> <!--需要一个name属性,必填--> <attribute> <name>name</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
3、在JSP中使用taglib
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="jsptag" uri="/myjsptag" %> <html> <head> <title>let'go</title> </head> <body> <form action="/test" method="post"> <%--这样就可以使用jspTag了,注意需要引入taglib--%> <div><jsptag:mytag name="yangyu">nihao</jsptag:mytag></div> <input type="text" id="para" name="para"/> <button type="submit" value="提交"/> </form> </body> </html>