首页 > 代码库 > 自定义标签库_tag

自定义标签库_tag

1)最简单的标签库

  1,继承Tag接口,重写doEndTag()方法,返回类型不同后面流程不一样

    想要jsp的内容必须重写了setPageContent()方法

    再JspWriter out = pageContent.getOut();

技术分享
package myTag;

import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class Copyright implements Tag {
    private PageContext pageContext;
    private Tag parent;

    @Override
    public int doEndTag() throws JspException {
        // TODO Auto-generated method stub
        JspWriter out = pageContext.getOut();
        try {
            out.println("<div align=center style=‘line-height:22px;"
                    + "font-size:12px;‘>");
            out.println(ResourceBundle.getBundle("copyright").getString(
                    "copyright"));
            out.println("</div>");
        } catch (IOException e) {
            throw new JspException(e);
        }

        return EVAL_PAGE;
    }

    @Override
    public int doStartTag() throws JspException {
        // TODO Auto-generated method stub
        return SKIP_BODY;
    }

    @Override
    public Tag getParent() {
        // TODO Auto-generated method stub
        return this.parent;
    }

    @Override
    public void release() {
        // TODO Auto-generated method stub

    }

    @Override
    public void setPageContext(PageContext pc) {
        // TODO Auto-generated method stub
        this.pageContext = pc;
    }

    @Override
    public void setParent(Tag t) {
        // TODO Auto-generated method stub
        this.parent = t;
    }
}
View Code

  2,在WEB-INF/目录下创建tld文件(new/other创建

  bodycontent有三个值,empty表示不可以有标签体,jsp表示可以有标签体,tagdependent可以有但不会执行

<taglib>
 <tlib-version>1.0</tlib-version>
 <jsp-version>1.2</jsp-version>
 <short-name>taglib</short-name>
 <tag>
     <name>copyright</name>
     <tagclass>myTag.Copyright</tagclass>
     <bodycontent>JSP</bodycontent>
 </tag>
</taglib>

   3,由于我用了资源文件

  ResourceBundle.getBundle("copyright").getString("copyright")

    所以src文件下一定要有这个文件的copyright属性

  4,在jsp中首先声明,<%@ taglib uri="WEB-INF/xxx.tld" prefix="taglib">

    下面就可以<taglib:copyright/>

 

自定义标签库_tag