1、创建自定义标签类
- 继承SimpleTagSupport类:所有自定义标签均继承至SimpleTagSupport
重写doTag()方法;
示例代码:
package taglibclass;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HelloWorldTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().write("hello world taglib" + new java.util.Date());
}
}
2、创建TLD文件,并配置自定义标签
- TDL标准文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.2</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>mytaglib</short-name>
<!--定义该标签库的URI,该值必须唯一,为调用时的标识符-->
<uri>mytaglib/mytag</uri>
<tag>
<!--定义标签名-->
<name>helloTag</name>
<!--定义标签类全名-->
<tag-class>taglibclass.HelloWorldTag</tag-class>
<!--定义标签体为空-->
<body-content>empty</body-content>
</tag>
</taglib>
3、在JSP文件中使用自定义标签
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!--导入标签库,url对于TLD文件中的URI,prefix是指定标签库前缀-->
<%@ taglib uri="mytaglib/mytag" prefix="mytag" %>
<!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>
<!--使用标签-->
<mytag:helloTag/><br>
</body>
</html>