自己封装JSTL 自定义标签

第一步,做一个类,派生自SimpleTagSupport,“alt+/”选重写doTag()方法。

public class TestTag extends SimpleTagSupport {
    private String outerTagName="p";

    public void setOuterTagName(String outerTagName) {
        this.outerTagName = outerTagName;
    }
    private int count;

    public void setCount(int count) {
        this.count = count;
    }

    @Override
    public void doTag() throws JspException, IOException {
        JspFragment frag = this.getJspBody(); //当前生成的片段
        this.getJspContext().getOut().write("<"+outerTagName+">");//添加的属性
        for(int i=0;i<count;i++){
        frag.invoke(null);//生成输出
        }
        this.getJspContext().getOut().write("</"+outerTagName+">");
    }
}

第二步,配置

在WEB-INF文件夹中新建一个XML.File文件,扩展名更改为tld,选择XML template,完成创建。

taglib为根元素

<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">

根元素下面写对整个文件的描述

<description>自定义jstl标签</description> 描述
<display-name>JSTL自定义标签</display-name> 显示的名字
<tlib-version>1.1</tlib-version> 版本
<short-name>c</short-name> 前缀
<uri>http://www.itnba.com/maya/myjstl</uri> 唯一标识

  <description>自定义jstl标签</description> 
  <display-name>JSTL自定义标签</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>http://www.itnba.com/maya/myjstl</uri>

后面写<tag>标签

<name>catch</name> 引用时:后面就是这个名字
<tag-class>com.itnba.maya.myel.TestTag</tag-class> com.itnba.maya.myel是第一步做的包名 TestTag是类名
<body-content>scriptless</body-content> 不能写脚本,即不能写<%%>
<required>false</required>是否必填,true是自动生成必须填,false可写可不写
<rtexprvalue>false</rtexprvalue>是否可以用el表达式<tag>

<tag>
  <description>
  ...描述
  </description>
  <name>catch</name> 
  <tag-class>com.itnba.maya.myel.TestTag</tag-class>
  <body-content>scriptless</body-content>
    <attribute>
    <description>
    第一条属性
    </description>
    <name>outerTagName</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    </attribute>
    

    <attribute>
    <description>
    第二条属性
    </description>
    <name>count</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    </attribute>
  </tag>
</taglib>

第三步,现在就可以引用这个JSTL自定义的标签了

先导一下写好的el函数,

prefix是在${}中用的名,uri是第二步配置中的那个唯一标识

<%@ taglib prefix="c" uri="http://www.itnba.com/maya/myjstl" %>

用prefix名:<tag>中<name>,后面就可以把写好的属性加上

<c:catch outerTagName="h3" count="2">
Hello Lee<br>
</c:catch>

这段代码应该显示三号标题,count是循环次数,两次,显示如下图。

 

转载于:https://www.cnblogs.com/liyh123/p/6395889.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值