自定义标签的入门

首先需要一个标签类

  • 首先需要继承TagSupport
  • 实现它其中的一个方法doStartTag()
public class MyTag extends TagSupport {

	@Override
	public int doStartTag() throws JspException {
		//获得一个输出对象
		JspWriter out = super.pageContext.getOut();
		try {
			out.print("<span>这个是自定义标签输出的内容</span>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doStartTag();
	}

书写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>
	<!-- 引用的时候使用的url -->
	<uri>http://xujiangchen/myTag/</uri>
	<display-name>Common Tag</display-name>
	<description>Common Tag library</description>

	<tag>
		<!-- 页面使用时所书写的标签名称 -->
		<name>out</name>
		<!-- 绑定自己所创建的类 -->
		<tag-class>com.xu.crm.utils.MyTag</tag-class>
		<body-content>JSP</body-content>
	</tag>
</taglib>

页面

<!--引入标签-->
<%@ taglib prefix="myTag" uri="http://xujiangchen/myTag/"%>
<!--使用标签-->
<myTag:out></myTag:out>

猜你喜欢

转载自blog.csdn.net/qq_43642812/article/details/84899500
今日推荐