自定义标签

来源:互联网 发布:带网络的电视机 编辑:程序博客网 时间:2024/05/29 15:32

      jsp中程序员可以自己定义标签。步骤如下:

    1:新建一个类,继承TagSupport类。TagSupport中有pageContext对象,我们可以获取request,response,out等jsp内置对象。

    2:我们可以重写doStartTag()方法或者doEndTag()方法,来定义需要执行标签的内容。

    3:当我们写好了tag类后,需要定义一个tld文件来描述标签。         4:在jsp中导入标签库,则我们自己开发的标签就可以使用了。如<%@ taglib uri="www.shizhan.com" prefix="shizhan"%>

     下面是tld文件的内容

      

<?xml version="1.0" encoding="UTF-8" ?><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">        <description>A tag library exercising SimpleTag handlers.</description>    <tlib-version>1.0</tlib-version>    <short-name>shizhan</short-name>    <uri>www.shizhan.com</uri>            <tag><description>Outputs the ip</description>        <name>ViewIP</name><tag-class>com.shizhan.ViewIPTage</tag-class><body-content>empty</body-content>    </tag> </taglib>

下面的代码是 jsp翻译成servlet后,执行标签体的代码内容,可以帮助我们理解好标签体的执行流程。

  

  private boolean _jspx_meth_shizhan_005fViewIP_005f0(PageContext _jspx_page_context)          throws Throwable {    PageContext pageContext = _jspx_page_context;    JspWriter out = _jspx_page_context.getOut();    //  shizhan:ViewIP    com.shizhan.ViewIPTage _jspx_th_shizhan_005fViewIP_005f0 = (com.shizhan.ViewIPTage) _005fjspx_005ftagPool_005fshizhan_005fViewIP_005fnobody.get(com.shizhan.ViewIPTage.class);    _jspx_th_shizhan_005fViewIP_005f0.setPageContext(_jspx_page_context);    _jspx_th_shizhan_005fViewIP_005f0.setParent(null);    int _jspx_eval_shizhan_005fViewIP_005f0 = _jspx_th_shizhan_005fViewIP_005f0.doStartTag();    if (_jspx_th_shizhan_005fViewIP_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {      _005fjspx_005ftagPool_005fshizhan_005fViewIP_005fnobody.reuse(_jspx_th_shizhan_005fViewIP_005f0);      return true;    }    _005fjspx_005ftagPool_005fshizhan_005fViewIP_005fnobody.reuse(_jspx_th_shizhan_005fViewIP_005f0);    return false;  }

1:创建标签体对象的java类对象。

2:先调用setPageContext()方法。

3:调用setParent()方法,如果有父标签,则把父标签的对象传递进来,否则传递null进来。

4:调用doStartTag()方法。

5:调用doEndTag()方法。

6:将标签类对象放入缓存中。

除了以上方法之外,我们还可以通过下列几个常量控制jsp页面的执行,他们是EVAL_BODY_INCLUDE,EVAL_PAGE, SKIP_BODY, SKIP_PAGE。例如在doStartTag()方法中返回SKIP_BODY的话,那么就会跳过标签的主体内容。在doEndTag()中返回EVAL_BODY_AGAIN的话,我们就可以控制标签体中的内容再次执行。

原创粉丝点击