首先,一定要在WEB-INF文件夹下创建一个tld文件
<?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">
<!-- 上面的代码不用动,下面的代码是关于标签的描述。关注short-name,他是标签显示的名称,即prefix -->
<!-- uri可以随便写,反正就是jar包中对应的代码,只要不重名就行 -->
<description>my 1.1 core library</description>
<display-name>my core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>my</short-name>
<uri>http://www.luke.com/my/core</uri>
<!-- 下面就是注册tag,tag-class是执行java代码的类的路径 ,body-content是是否为自结束标签,比如img
attribute是是否有参数,required是指是否为必须,rtexprvalue是运行时是否可以获取表达式的值,
一般为true-->
<tag>
<name>helloTag</name>
<tag-class>com.anseon.day10.HelloTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>src</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
以上是自定义标签的部分代码
然后是写执行的Java代码
public class HelloTag extends SimpleTagSupport {
private String src;
public void setSrc(String src) {
this.src = src;
}
@Override
public void doTag() throws JspException, IOException {
PageContext context = (PageContext) getJspContext();
InputStream in = context.getServletContext().getResourceAsStream(src);
BufferedReader bufw = new BufferedReader(new InputStreamReader(in));
String str = null;
while((str = bufw.readLine())!=null){
context.getOut().print(str+"<br>");
}
bufw.close();
}
}
注意,如果标签有属性,因为用了反射,所以一定要声明属性的参数,即上面代码的src,然后一定要有setSrc的方法,这样才能通过反射将标签里面的值赋值过来自定义标签可以继承SimpleTagSupport,或者可以实现SimpleTag接口,一般用继承的,此时关注getJspContext()方法和getJspBody().invoke(null)方法,前者是获取上下文对象的,后者的invoke方法,如果是null就会直接输出到浏览器,否者输出到参数里面