自定义标签库是一种非常优秀的组件技术。通过使用自定义标签库,可以在简单的标签中封装复杂的功能。
- 新建标签处理类"HelloWorldTag.java",继承TagSupport(import tomact\lib\jsp-api.jar) 父类
//Comment1: *.java must in package xxx //Comment2: File locate \Project\"src"\package package tag; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; public class HelloWorldTag extends TagSupport { /** * */ //Comment3: must be generated private static final long serialVersionUID = 1L; public int doEndTag() throws JspTagException { try { pageContext.getOut().write("Hello World"); } catch (IOException ex) { throw new JspTagException("Error"); } return EVAL_PAGE; } }
注释1: JAVA类必须包含在package中
注释2: JAVA类文件必须位于 "工程\package\*.java"
Pic1: Eclipse Project Explorer
Pic2: *.java package file folder
注释3: 必须生成 serialVersionUID
2. 建立TLD 文件"HelloWorldTag.tld"
<?xml version="1.0" encoding="UTF-8"?> <!--Comment4 Add !DOCTYPE --> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_l_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <tag> <!--Comment5 *.jsp <customTag:name> ref --> <name>helloworld</name> <tag-class>tag.HelloWorldTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
注释四: tld文件Eclipse中不能直接创建,选创建*.xml文件,然后重命名后缀.注意Comment5,6(下)对应*.jsp中如何使用自定义标签
3. 在web.xml 文件中增加标签库定义<jsp-config></jsp-config>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>JSPWeb</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <jsp-config> <taglib> <!-- Comment6 *.jsp "<%@ taglib uri= " Ref --> <taglib-uri>/tag/HelloWorldTag</taglib-uri> <taglib-location>/WEB-INF/HelloWorldTag.tld</taglib-location> </taglib> </jsp-config> </web-app>
4. jsp(JspTag.jsp)中使用自定义标签
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!-- ref Comment6 -->
<%@ taglib uri="/tag/HelloWorldTag" prefix="tag" %>
<!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>
<!-- ref Comment5 -->
<tag:helloworld />
</body>
</html>
5. Eclipse->Run->Debug As->Debug on Server(前提Server已配置好), 输出结果 "Hello World".
6. 代码下载路径: http://download.csdn.net/detail/badphilipw/6461861