前言
在我们的日常开发中,虽然标准jstl库能满足我们的大部分需求,但是在没办法满足的时候就需要我们 使用自定的标签,
说明
这里只演示最简单的标签开发流程,便于熟悉开发流程
开发流程
结构图
编写标签类
需要继承TagSupport类或者其他实现了jsptag接口的类或者接口.
/**
* 自定义标签类
* @author EumJi
*
*/
public class ExampleTag extends TagSupport{
@Override
public int doStartTag()
throws JspException {
try {
pageContext.getOut().print(
"这是我的第一个标签!");
}
catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
}
编写tld文件
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>A tag library exercising SimpleTag handlers.
</description>
<tlib-version>1.0
</tlib-version>
<short-name>SimpleTagLibrary
</short-name>
<uri>/example
</uri>
<tag>
<description>Outputs 第一个标签
</description>
<name>first
</name>
<tag-class>com.jsu.tag.ExampleTag
</tag-class>
<body-content>empty
</body-content>
</tag>
</taglib>
在jsp页面中引入标签并使用
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/example" prefix="ex" %>>
<!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=ISO-8859-1">
<title>Insert title here
</title>
</head>
<body>
<h1>测试案例
</h1>
<ex:first/>
</body>
</html>
实验结果
更多代码
请移步:源代码