BlogJava 联系 聚合 管理  

Blog Stats

随笔档案

文章档案

Infernu的Google site


Infernus-JXH

此文主要是实现不处理标签库的自定义标签,步骤如下:
首先写一个类,继承TagSupport,重写doStartTag(),doEndTag()如果要处理标签体,需要重写doAfterBody()。
public class MyFirstTag extends TagSupport {
    
private String format = "yyyy.MM.dd hh:mm:ss";

    @Override
    
public int doStartTag() throws JspException {
        JspWriter out 
= pageContext.getOut();
        SimpleDateFormat sdf 
= new SimpleDateFormat(format);
        
try {
            out.println(
"<table border='1'><tr><td bgcolor='blue'>");
            out.println(
"<font color='yellow' size='7'>");
            out.println(sdf.format(
new java.util.Date()));
            out.println(
"</font>");
            out.println(
"</td></tr></table>");
        }

        
catch (IOException e) {
            e.printStackTrace();
        }

        
return SKIP_BODY;    //跳过标签体[不需要处理标签的标签体]
    }

    
    
public void setFormat(String format){
        
this.format = format;
    }

    
}
其次,配置tld文件(标签库描述文件):

<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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version
="2.0"><!-- 上面这段可以从JSTL里COPY -->
    
    
<description>My First Custom Tag Library</description><!-- 叙述 -->
    
<display-name></display-name><!-- 显示的名字 -->
    
<tlib-version>1.0</tlib-version><!-- 版本 -->
    
<short-name>MFCTL</short-name><!-- 短的名字 -->
    
<uri>cj</uri><!-- 全局唯一的uri,一般为"http:// ",此文只做示例,太短的话容易重复。与下文web.xml的配置应一致  -->
    
    
<tag>
        
<name>time</name><!-- 调用的名字,如<前缀:time/> -->
        
<tag-class>com.tsinghuait.tags.MyFirstTag</tag-class><!-- 具体的类 -->
        
<body-content>empty</body-content><!-- 标签体内容可以为空 -->
    
</tag>
    

然后,配置web.xml,告诉服务器有这么一个标签库。
    <jsp-config>
        
<taglib>
            
<taglib-uri>cj</taglib-uri><!-- 全局唯一的uri -->
            
<taglib-location>/WEB-INF/tld/Mytag.tld</taglib-location><!-- 标签库的描述文件位置 -->
        
</taglib>
    
</jsp-config>

最后,写一个页面用<%@taglib %>指令给定前缀和uri,调用标签。
<%@taglib prefix="lh" uri="cj"%>

<lh:time/>

posted on 2009-11-27 10:11 Infernus 阅读(199) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: