- 创建一个类,引入外部jsp-api.jar包(在tomcat 下lib包里有),这个类继承SimpleTagSupport
- 重写doTag()方法。
jspprojec包下的helloTag类:
1 public class helloTag extends SimpleTagSupport{
2
3 @Override
4 public void doTag() throws JspException, IOException {
5
6
7 JspWriter out=this.getJspContext().getOut();
8 out.print("你好我是自定义标签");
9 }
10
11 }
- 定义配置文件,这个文件放在webContent目录下的tags包里,文件扩展名为.tld 。
<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">
<tlib-version>1.2</tlib-version>
<short-name>my</short-name>
<uri>my/jsp/jstl/my_hi</uri>
<tag>
<name>hi</name> //标签名
<tag-class>jspprojec.helloTag</tag-class> //自定义标签类
<body-content>empty</body-content>
</tag>
</taglib>
- 在jsp中使用自定义标签:
1 <%@page import="java.util.ArrayList,java.util.ArrayList,jspprojec.Student"%>
2 <%@ page language="java" contentType="text/html; charset=UTF-8"
3 pageEncoding="UTF-8"%>
4 <%@ taglib prefix="my" uri="tags/my.tld" %>
5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6 <html>
7 <head>
8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
9 <title>Insert title here</title>
10 </head>
11 <body>
12
13 <my:hi/>
14
15 </body>
16 </html>
结果: