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" οnclick="alert(232232323);" /></util:ctl>
完成
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值