自定义标签的实现思路:
}
1.定义一个继承
SimpleTagSupport类的子类,重写doTag()方法
2.定义一个tld文件,将文件放在WEB-INF目录下,容器在加载时会自动加载
3.前台JSP页面中以taglib的形式引入自定义的标签,进行使用
注:如果需要在标签中加入属性,需要在标签的实现类中为每个属性加入getter,setter方法,并在tld文件的<tag>标签中加入<attribute>标签
简单的HELLO WORLD实现
1.
public class HelloWorld extends SimpleTagSupport{
@Override
public void doTag(){
try {
getJspContext().getOut().write("hello world");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.
<?xml version="1.0" encoding="GBK"?>
<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 web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>mytaglib</short-name>
<!-- 定义该标签库的URI -->
<uri>mytaglib</uri>
<!-- 定义第一个标签 -->
<tag>
<!-- 定义标签名 -->
<name>helloWorld</name>
<!-- 定义标签处理类 -->
<tag-class>com.HelloWorld</tag-class>
<!-- 定义标签体为空 -->
<body-content>empty</body-content>
</tag>
</taglib>
3.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="mytaglib" prefix="tt"%>
<!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>
<tt:helloWorld/>
</body>
</
html
>