今天看书摸索了一下午终于弄清楚 JSP Taglib 的基本原理,做下笔记以备忘.
首先要写好一个java类来定义自己的Tag,这个类必须继承javax.servlet.jsp.tagext.SimpleTagSupport类才可以!!!
HelloJSP_Taglib.java 代码如下:
package mytag; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class HelloJSP_Taglib extends SimpleTagSupport { //自定义Tag @Override public void doTag() throws JspException, IOException { this.getJspContext().getOut().write("This is my first Taglib programme.<br>"); this.getJspContext().getOut().write("Use the Taglib you can do something like the " + "Mmakeup Language.<br>"); } }
其次在web-app的WEB-INF目录或其子目录下写好 *.tld 配置文件,它主要用于Tag使用时查找具体的“实现”以及使用Tag时的前缀等...
HelloJSP_Taglib.tld 文件里的内容如下:
<?xml version="1.0" encoding="UTF-8"?> <taglib 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-jsptalib_2_5.xsd" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>mytag</short-name> <uri>/hellojsptaglib</uri> <tag> <name>HelloJSP_Taglib</name> <tag-class>mytag.HelloJSP_Taglib</tag-class> <body-content>empty</body-content></tag> </taglib>
最后写一个JSP文件测试自己的Tag
TestTaglib.jsp文件如下:
<%@ page language="java" import="mytag.*" pageEncoding="GB18030"%> <%@ taglib uri="/hellojsptaglib" prefix="mytag" %> <%@ taglib uri="/productlisttaglib" prefix="product" %> <!-- 注意这里uri要与上面的HelloJSP_Taglib.tld 文件里的uri 内容保持一致 --> <!-- prefix 内容要与HelloJSP_Taglib.tld 文件里的short-name 内容保持一致 --> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+ ":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'TestTaglib.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <mytag:HelloJSP_Taglib/> <!-- 这里使用了自己定义的Tag --> </center> </body> </html>
测试完成,浏览器可以解释自定义的Tag啦..........
1 楼
i5cn
2008-09-19
不是浏览器解释自定义的Tag
2 楼
dishell
2008-09-20
i5cn 写道
不是浏览器解释自定义的Tag
请问那应该是怎样呢?