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>
  • 相关阅读:
    398. Random Pick Index
    382. Linked List Random Node
    645. Set Mismatch
    174. Dungeon Game
    264. Ugly Number II
    115. Distinct Subsequences
    372. Super Pow
    LeetCode 242 有效的字母异位词
    LeetCode 78 子集
    LeetCode 404 左叶子之和
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/1950674.html
Copyright © 2011-2022 走看看