我们可以使用自定义URI来告知Web容器关于tld文件的位置。在这种情况下,我们需要在web.xml中定义taglib元素。Web容器从web.xml文件获取指定URI的tld文件信息。

在JSP自定义标签中使用自定义URI的示例

在这个例子中,我们将在JSP文件中使用自定义URI。对于这个应用程序,我们需要关注4个文件:

  • index.jsp
  • web.xml
  • mytags.tld
  • PrintDate.java

index.jsp

<%@ taglib uri="mytags" prefix="m" %>  
Today is: <m:today></m:today>  

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE web-app   
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   
  "http://java.sun.com/dtd/web-app_2_3.dtd">   
  
<web-app>  
  
<jsp-config>  
<taglib>  
<taglib-uri>mytags</taglib-uri>  
<taglib-location>/WEB-INF/mytags.tld</taglib-location>  
</taglib>  
</jsp-config>  
  
</web-app>  

mytags.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>  
<!DOCTYPE taglib  
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"  
        "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">  
  
<taglib>  
  <tlib-version>1.0</tlib-version>  
  <jsp-version>1.2</jsp-version>  
  <short-name>simple</short-name>  
  <uri>mytags</uri>  
  <description>A simple tab library for the examples</description>  
  
  <tag>  
    <name>today</name>  
    <tag-class>cn.javatiku.taghandler.PrintDate</tag-class>  
  </tag>  
</taglib>  

PrintDate.java

package cn.javatiku.taghandler;  
  
import javax.servlet.jsp.JspException;  
import javax.servlet.jsp.JspWriter;  
import javax.servlet.jsp.tagext.TagSupport;  
  
public class PrintDate extends TagSupport{  
  
public int doStartTag() throws JspException {  
    JspWriter out=pageContext.getOut();  
    try{  
        out.print(java.util.Calendar.getInstance().getTime());  
    }catch(Exception e){e.printStackTrace();}  
      
    return SKIP_BODY;  
    }  
      
  
}  

标签: JSP, JSP教程, JSP技术, JSP快速入门, JSP简单用法, JSP编程, JSP下载, JSP基本语法, JSP安装教程, JSP库, JSP指南, JSP基础教程, JSP初级教程, JSP进阶教程