自定义tag标签-实现long类型转换成Date类型

数据库里存储的是bigint型的时间,entity实体中存放的是long类型的标签,现在想输出到jsp页面,由于使用的是jstl标签,而要显示的是可读的时间类型,找来找去有个 fmt:formatDate可以转化,但是只能将String类型的转成date型,long型则不可以,思考了好久,又不想破环jsp页面这种标签结构,参考网上jstl标签编写方法,如下:
第一步 写一个类继承TagSupport,实现doStartTag() 方法。

package com.pp.yxx.util.tags;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport; import com.pp.yxx.util.DateUtils; /**
* 用于页面 jstl时间格式化
*
* @Title: JSTLDateUtils.java
* @Description: 转换Long时间戳为时间格式
* @author phpdragon
* @date 2014 -3- 4 下午06:28:51
*/
public class Long2DateTag extends TagSupport { private static final long serialVersionUID = 6464168398214506236L; private String value;
private String format; @Override
public int doStartTag() throws JspException {
String s = format == null ? DateUtils.timestamp2Time(value) : DateUtils
.timestamp2Time(value, format);
try {
pageContext.getOut().write(s);
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
} public void setValue(String value) {
this.value = value;
} public void setFormat(String format) {
this.format = format;
} }

第二步 编写tld文件,extendtag.tld,放在/WEB-INF目录下

<?xml version="1.0" encoding= "UTF-8"?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>ext</short-name>
<uri>/extendTags</uri>
<tag>
<description>
转换long型参数为时间格式
</description>
<name>long2date</name>
<tag-class>com.pp.yxx.util.tags.Long2DateTag</tag-class>
<!--如果不需要标签体则设置empty,反之设定jsp -->
<body-content>JSP</body-content>
<attribute>
<description>
需要装换的值
</description>
<name>value</name>
<!-- 是否是必须,如果非必须没设置则为空 -->
<required>true</required>
<!-- 是否可在属性中使用表达式 -->
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>
转换格式
</description>
<name>format</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

第三步  在web.xml中加入引用

<!-- 自定义TAG标签 -->
<jsp-config>
<taglib>
<taglib-uri>/extendTags</taglib-uri>
<!-- tld文件所在的位置 -->
<taglib-location>/WEB-INF/extendtag.tld</taglib-location>
</taglib>
</jsp-config>

第四步 在jsp页面开始使用

<%@ taglib uri="/extendTags" prefix="ext"%>
<ext:long2date value ="${publish}" format="yyyy-MM-dd HH:mm:ss" />

上述方式即可实现所述功能!

参考:http://hfutxf.iteye.com/blog/673472

上一篇:Oracle误删除数据恢复


下一篇:face,Pool