1.tld文件(放在WEB-INF下面)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib PUBLIC "-//Sun xxxxx">
<taglib>
<tlib-version>1.0</tlb-version>
<jsp-version>1.2</jsp-version>
<uri>http://xxx/web/tag</url>
<tag>
<name>cache</name>
<tag-class>com.xxx.controller.cache.Cache</tag-class>
<body-content>empty</body-content>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>code</name>
<required>true</required>
</attribute>
</tag>
</taglib>
2.对应的Java文件:继承SimpleTagSupport类并重写的doTag()方法,方法中使用了getJspContext()方法来获取当前的JspContext对象,并将内容传递给JspWriter对象
package com.xxx.controller.cache
public class Cache extends SimpleTagSupport{
private ICacheService cacheService;
private String value;
private String code;
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
if(StringUtils.isBlank(code) || StringUtils.isBlank(value)){
out.write("");
return;
}
// 这里项目中是用到了缓存,在项目启动时就将数据库词典加载到内存中
cacheService = SpringBeanUtils.getBean(ICacheService.class);
Map<Object, Object> map = cacheService.getHashFormRedisByKey(
Constants.REDIS_HEADER_DICT+code);
if(map == null || map.isEmpty()){
out.write("");
return;
}
out.write(map.get(value)==null?"":String.valueOf(map.get(value)));
}
public void setValue(String value){ this.value = value; }
public void setCode(String code){ this.code = code; }
}
3.应用
<%@ taglib prefix="i" uri="http://xxx/web/tag" %>
<i:cache code="status" value="1" />