一、基本概念
1.标签(Tag)
标签是一种XML元素 可以通过标签能够使jsp页面变得简洁
并且易于维护
2 标签库(Tag library)
由一系列功能相似,逻辑相互联系的标签构成集合
3 标签库描述文件(Tag Library Descriptor)
标签库描述文件是一个XML文件 这个文件提供了标签库中类和jsp
中标签的映射关系 是一个配置文件 和web.xml有点类似
4 标签处理类(Tag Handle Class)
是一个Java类 集成了TagSupport 也可以实现SimpleTag接口 通过这些类
重写其相应的方法 实现自定义标签的具体的功能
以下是一个简单的例子
新建一个标签处理类
package com.newture.mytag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class HelloWorldTag extends TagSupport{
/**
*
*/
private static final long serialVersionUID = -7609301577715095108L;
@Override
public int doEndTag() throws JspException {
try {
pageContext.getOut().write("Hello World 标签");
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
}
再在WEB-INF建立标签库描述文件(Tag Library Descriptor)
<?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>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>mytags</short-name>
<tag>
<name>helloworld</name>
<tag-class>com.newture.mytag.HelloWorldTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
再在web.xml进行相应的简单的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/tld/helloworld</taglib-uri>
<taglib-location>/WEB-INF/tlds/helloworld.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
在简单的应用下自己的自定义的标签
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/tld/helloworld" prefix="mytag" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<h1>自定义标签:</h1><br>
<mytag:helloworld></mytag:helloworld>
</body>
</html>
jsp页面显示了一个hello world的结果
这个程序要注意几点 就是
.tld与xml中文档的版本要一致