自定义Tag实现SimpleTagSupport,提供type和value两个参数
<t:convert type="cert_type" value="${certBriefInfo.certType }" />
1.在项目启动时,初始化标签type对应枚举类
public class ConvertTagConfig {
public static void initConvertTag() {
Map<String, Map<Integer, String>> convertPool = getConvertPool();
ConvertTag.register(convertPool);
}
private static Map<String, Map<Integer, String>> getConvertPool() {
Map<String, Map<Integer, String>> map = new HashMap<>();
map.put("cert_type", MapUtils.concertEnumToMap(CertTypeEnum.values()));
map.put("biz_type", MapUtils.concertEnumToMap(BizTypeEnum.values()));
map.put("register_status", MapUtils.concertEnumToMap(RegisterStatusEnum.values()));
map.put("pay_mode", MapUtils.concertEnumToMap(PayModeEnum.values()));
map.put("pay_online_status", MapUtils.concertEnumToMap(PayOnlineStatusEnum.values()));
map.put("cert_status", MapUtils.concertEnumToMap(CertStatusEnum.values()));
map.put("yes_or_no",MapUtils.concertEnumToMap(YesOrNoEnum.values()));
map.put("org_nature",MapUtils.concertEnumToMap(OrgNatureEnum.values()));
return map;
}
}
2.后台处理标签参数
@Getter
@Setter
public class ConvertTag extends SimpleTagSupport {
private String type;
private Integer value;
private static final Map<String, Map<Integer, String>> pool = new HashMap<>();
@Override
public void doTag() throws JspException, IOException {
JspContext context = getJspContext();
/* 得到输出对象 */
JspWriter out = context.getOut();
out.print(pool.get(type).get(value));
super.doTag();
}
public static void register(Map<String, Map<Integer, String>> param) throws DuplicateConvertException {
for(Map.Entry<String, Map<Integer, String>> entry:param.entrySet()){
pool.put(entry.getKey(),entry.getValue());
}
}
}
3.自定义gov-tags.tld文件,并放在/WEB-INF目录下
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" 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">
<tlib-version>1.0</tlib-version>
<short-name>t</short-name>
<uri>/gov-tags</uri>
<tag>
<name>convert</name>
<tag-class>com.zjca.govca.config.tag.ConvertTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>type</name>
<required>true</required>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<!--是否允许使用表达式-->
<rtexprvalue>true</rtexprvalue>
</attribute>
<!--
tld文件中有四种标签体类型 :empty JSP scriptless tagdepentend
在简单标签(SampleTag)中标签体body-content的值只允许是empty和scriptless,不允许设置成JSP,如果设置成JSP就会出现异常
在传统标签中标签体body-content的值只允许是empty和JSP
如果标签体body-content的值设置成tagdepentend,那么就表示标签体里面的内容是给标签处理器类使用的,
例如:开发一个查询用户的sql标签,此时标签体重的SQL语句就是给SQL标签的标签处理器来使用的
<gacl:sql>SELECT * FROM USER</gacl:sql>
在这种情况下,sql标签的<body-content>就要设置成tagdepentend,tagdepentend用得比较少,了解一下即可
-->
</tag>
</taglib>
在使用时需要在页面引用库
<%@ taglib prefix="t" uri="/gov-tags"%>