步骤:
- 编写自定义标签类
package com.itheima.crm.utils;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTag extends TagSupport {
/*
*自定义标签
*作用:向页面输出html元素
*
*/
@Override
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
JspWriter out = super.pageContext.getOut();
try {
out.println("<span>这个是自定义标签输出的内容<span>");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
}
2.编写mytag.tld文件(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://itheima/myTag</uri>
<display-name>Common Tag</display-name>
<description>Common Tag library</description>
<tag>
<name>out</name>
<tag-class>com.itheima.crm.utils.MyTag</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
3.tag.jsp中使用(使用自定义标签,页面引入的方式)
<%@ 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://itheima/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>