jsp-自定义标签Tag

背景:公司框架好烂啊,据说部门下拉选之类的都没有封装好,还需要写方法(拷贝js,jsp以及后台接口)过去。字典表也没用过。新项目要启动了,准备写一些标签,方便之后使用。所以先写个demo联一下,之后把字典,部门,用户之类的封一个标签。

1.先写个tld文件

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

    <description>JSTL 1.1 functions library</description>
    <display-name>JSTL functions sys</display-name>
    <tlib-version>1.1</tlib-version>
    <short-name>sys</short-name>
    <uri>http://java.sun.com/jsp/jstl/functionss</uri>

  <tag>
    <name>dict</name>
    <tag-class>cn.bszx.base.action.sys.DictTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
      <name>dictType</name> 
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
      <name>dictKey</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
</taglib>

其中需要注意的就是<tag>标签里面的内容name为标签名,tag-class为实现该标签的class的地址,body-content为jsp意思是接收jsp的所有语法。attribute为标签的属性,我这个标签有两个属性,分别为dictType和dictKey  required意思为是否必填,rtexprvalue意思为能否使用表达式获取值。

2.填写实现该标签的java文件。

public class DictTag extends BodyTagSupport {
        private String dictType;
        private  String dictKey;

    @Override
    public int doStartTag() throws JspException {
        String html = "";
        if("0".equals(dictKey)){
            html = "<span>男</span>";
        }else if("1".equals(dictKey)){
            html = "<span>女</span>";
        }
        try{
            pageContext.getOut().write(html);
        }catch (Exception e){
            e.printStackTrace();
        }
       return super.doStartTag();
    }

    public String getDictType() {
        return dictType;
    }

    public void setDictType(String dictType) {
        this.dictType = dictType;
    }

    public String getDictKey() {
        return dictKey;
    }

    public void setDictKey(String dictKey) {
        this.dictKey = dictKey;
    }
}

java代码需要继承BodyTagSupport。填写属性,即标签属性dictType和dictKey。填写属性的get\set方法。重写doStartTag方法,将需要输出的标签按照HTML格式写出来即可。

3.前台引用该标签

导入自定义标签地址,用prefix指代

<%@ taglib prefix="sys" uri="/jsp/tlds/dict.tld"%>

引用的时候<sys:dict dictType="1" dictKey="1"/>即可。页面编译的时候会把其转变<span>女</span>

4.使用场景

对于常用的内容可以制作自定义标签来进行使用。比如用户列表,部门列表之类的。这样的话,以后只需要引用标签,<sys:dept/>就可以了。而不需要每次都编写获取部门信息的ajax

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值