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>
  • 相关阅读:
    UVa-133-救济金发放
    UVa-340-猜数字
    UVa-1584-环状序列
    UVa-1585-得分
    UVa-1586-分子量
    BZOJ-3289: Mato的文件管理(莫队算法+树状数组)
    HDU-2824 The Euler function(欧拉函数)
    2017年10月12日22:27:20
    HDU-4715 Difference Between Primes(线性筛法)
    POJ-1185 炮兵阵地(状态压缩DP)
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/1950674.html
Copyright © 2011-2022 走看看