编写自定义标签类:
继承TagSupport类
public class MyTag extends TagSupport {
@Override
public int doStartTag() throws JspException {
JspWriter out = super.pageContext.getOut();
try {
out.print("<p>这里是自定义标签输出的内容</p>");
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
}
编写标签描述文件(MyTag.tld):
<?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>2.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>myTag</short-name>
<uri>http://utils/MyTag/</uri>
<tag>
<name>out</name>
<tag-class>utils.MyTag</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
在页面(MyTag.jsp)中使用标签
prefix="myTag"中的myTag对应.tld中的short-name
uri:对应tld中的uri
.tld中声明了out标签,所以这里有out标签
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="myTag" uri="http://utils/MyTag/"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>自定义标签</title>
</head>
<body>
<myTag:out></myTag:out>
</body>
</html>
访问jsp,就会输出out.print()中的内容