JSP 自定义标签 BodyTagSupport

自定义标签分成4部
[red]1. 创建tld文件,在WEB-INFO文件夹下创建tld文件夹,在tld文件夹下创建util.tld文件,内容如下:[/red]
<?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">   
     <tlib-version>1.0</tlib-version>   
     <short-name>util</short-name>   
     <uri>http://langhua.com/taglib/util</uri>   
     <tag>
     <name>ctl</name>
     <tag-class>com.test.tag.CtlTag</tag-class>
     <body-content>JSP</body-content>
     <attribute>
     <name>code</name>
     <required>true</required>
     <rtexprvalue>true</rtexprvalue>
     </attribute>
     </tag>
</taglib>   

[red]2.修改web.xml文件[/red]
<jsp-config> 
    <taglib> 
      <taglib-uri>util</taglib-uri> 
      <taglib-location>/WEB-INF/tld/util.tld</taglib-location> 
    </taglib> 
  </jsp-config>

[red]3. 创建类com.test.tag.CtlTag[/red]
package com.test.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class CtlTag extends BodyTagSupport {

private String code ;

public int doAfterBody() {
System.out.println("----------doAfterBody------------");
BodyContent bodyContent = getBodyContent() ;
String html = bodyContent.getString() ;
JspWriter out = bodyContent.getEnclosingWriter();
if(code.equals("show")){
try {
out.println(html);
} catch (IOException e) {
e.printStackTrace();
}
}
return SKIP_BODY;
}

@Override 
    public int doEndTag() throws JspException { 
        System.out.println("---------doEndTag()----------"); 
        return super.doEndTag(); 
    } 
 
    @Override 
    public void doInitBody() throws JspException { 
        System.out.println("---------doInitBody()----------"); 
        super.doInitBody(); 
    } 
 
    @Override 
    public int doStartTag() throws JspException { 
        System.out.println("---------doStartTag()----------"); 
        return super.doStartTag(); 
    } 
   
   
public String getCode() {
return code;
}

public void setCode(String code) throws JspException {
//ExpressionEvaluatorManager.evaluate("code", code.toString(), Object.class, this, pageContext);
this.code = code ;
}

}
[red]4. 在JSP页面中引用[/red]
<%@ taglib prefix="util" uri="http://langhua.com/taglib/util"%>   
Weather it can be shown below :

<util:ctl code="show"><input id="test" name="test" type="button" value="Button" onclick="alert(232232323);" /></util:ctl>
完成

你可能感兴趣的:(TagSupport)