自定义jsp标签

1.新建一个类继承自TagSupport、BodyTagSupport或实现Tag接口

//对应一个jsp标签
public class MyTag extends TagSupport {
    private JspWriter writer = null;
  //对应到jsp标签的属性
    private String showMsg;
   //遇到<调用
   //合法返回值EVAL_BODY_INCLUDE(显示标签体内容)与SKIP_BODY(不显示标签体内容)
    @Override
    public int doStartTag() throws JspException {
        return super.doStartTag();
    }
  //遇到>调用
  //合法返回值EVAL_PAGE(继续处理后续标签)与SKIP_PAGE(不处理后续表情)
    @Override
    public int doEndTag() throws JspException {
    //获得PageContext对象
        writer = this.pageContext.getOut();
        try{
            writer.write(showMeg);
        }catch (IOException ie){
            ie.printStackTrace();
        }
        return super.doEndTag();
    }
  //必须提供setter方法
    public void setShowMsg(String showMeg) {
        this.showMeg = showMeg;
    }
}
  1. 新建一个myxxx.tld文件,放于WEB-INF目录/其子目录下,用于映射关系
<?xml version="1.0" encoding="ISO-8859-1"?>

<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>myshortname</short-name>
    <uri>http://mycompany.com</uri>
    <!--加入自定义标签的定义-->
    <tag>
        <name>my1</name>
        <tag-class>tag.MyTag</tag-class>
        <body-content>JSP</body-content>
        <attribute>
            <name>showMsg</name>
       <!--配置是否必须-->
            <required>true</required>
        </attribute>
    </tag>

</taglib>
  1. 在web.xml文件中配置标签库uri
<jsp-config>
        <taglib>
            <taglib-uri>http://mycompany.com</taglib-uri>
            <taglib-location>/WEB-INF/mytag.tld</taglib-location>
        </taglib>
</jsp-config>
  1. 使用:引入taglib,然后中,pre为标签库,showMsg对应到自定义类,value为自定义类的实例域。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值