zoukankan      html  css  js  c++  java
  • jsp 自定义标签的写法

    1.定义标签类。

    标签扩展 BodyTagSupport 类。

    代码
    package testtag;

    import java.io.IOException;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.JspTagException;
    import javax.servlet.jsp.JspWriter;
    import javax.servlet.jsp.tagext.BodyTagSupport;
    import javax.servlet.jsp.tagext.TagSupport;

    public class LinkTag extends BodyTagSupport {

        
    public LinkTag() {
            
    // TODO Auto-generated constructor stub
        }
        
        
    private String href="";
        
        
    public String getHref() {
            
    return href;
        }

        
    public void setHref(String href) {
            
    this.href = href;
        }

        
    public int doStartTag() throws JspTagException {    
            
    return EVAL_BODY_BUFFERED;
          }
          
          
    public int doEndTag() throws JspTagException {
              
            String body 
    = this.getBodyContent().getString();
            HttpServletRequest request 
    = (HttpServletRequest)pageContext.getRequest();
            
            
    try {
                JspWriter writer
    = pageContext.getOut();
                String str
    ="<a href='"+this.href+"'>"+body+"</a>";
                pageContext.getOut().print(str);
            }
            
    catch (IOException e) {
              
    throw new JspTagException(e.getMessage());
            }
            
    return SKIP_BODY;
          }
    }

    2.定义标签文件 MyTagLib.tld。

    代码
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <tag>
      
    <name>linktag</name>
      
    <tag-class>testtag.LinkTag</tag-class>
      
    <body-content>jsp</body-content>
      
    <attribute>
        
    <name>href</name>
        
    <required>true</required>
        
    <rtexprvalue>true</rtexprvalue>
      
    </attribute>
    </tag>

    </taglib>

    3.在web.xml中添加引用。

    <jsp-config>
            
    <taglib>
                
    <taglib-uri>MyTagLib</taglib-uri>
                
    <taglib-location>/WEB-INF/MyTagLib.tld</taglib-location>
            
    </taglib>
        
    </jsp-config>

    4.在页面中调用自定义标签。

    <%@taglib uri="MyTagLib" prefix="mytag"%>
    <mytag:linktag href="http://www.baidu.com">测试标签</mytag:linktag>
  • 相关阅读:
    JavaScript函数式编程——柯里化
    JavaScript使用纯函数避免bug
    ES6入门五:箭头函数、函数与ES6新语法
    图解--二分查找树
    电梯引发的思考
    VIM
    vs 2017
    多线程系列(四):Task
    多线程系列(三):线程池基础
    Docker for windows : 安装Redis
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/1950674.html
Copyright © 2011-2022 走看看