数据库里存储的是long型的时间,现在想输出到jsp页面,由于使用的是jstl标签,而要显示的是可读的时间类型,找来找去有个fmt:formatDate可以转化,但是只能转date型,long型则不可以,思考了好久,又不想破环jsp页面这种标签结构,决定自己下个转换的标签,说干就干,开始干,参考网上jstl标签编写方法,如下:
第一步,写一个类继承TagSupport,实现doStartTag() 方法。
- public class DateTag extends TagSupport {
- private static final long serialVersionUID = 6464168398214506236L;
- private String value;
- @Override
- public int doStartTag() throws JspException {
- String vv = ""+value;
- long time = Long.valueOf(vv);
- Calendar c = Calendar.getInstance();
- c.setTimeInMillis(time);
- SimpleDateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String s = dateformat.format(c.getTime());
- try {
- pageContext.getOut().write(s);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return super.doStartTag();
- }
- public void setValue(String value) {
- this.value = value;
- }
- }
public class DateTag extends TagSupport {
private static final long serialVersionUID = 6464168398214506236L;
private String value;
@Override
public int doStartTag() throws JspException {
String vv = ""+value;
long time = Long.valueOf(vv);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
SimpleDateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = dateformat.format(c.getTime());
try {
pageContext.getOut().write(s);
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
public void setValue(String value) {
this.value = value;
}
}
第二步。编写tld文件,datetag.tld
- <?xml version="1.0" encoding="UTF-8"?>
- <taglib>
- <tlib-version>1.0</tlib-version>
- <jsp-version>1.2</jsp-version>
- <tag>
- <name>date</name>
- <tag-class>com.util.DateTag</tag-class>
- <body-content>JSP</body-content>
- <attribute>
- <name>value</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- </tag>
- </taglib>
<?xml version="1.0" encoding="UTF-8"?> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <tag> <name>date</name> <tag-class>com.util.DateTag</tag-class> <body-content>JSP</body-content> <attribute> <name>value</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>
第三步,在web.xml中加入引用
- <taglib>
- <taglib-uri>/tags</taglib-uri>
- <taglib-location>/WEB-INF/datetag.tld</taglib-location>
- </taglib>
<taglib> <taglib-uri>/tags</taglib-uri> <taglib-location>/WEB-INF/datetag.tld</taglib-location> </taglib>
第四步,在jsp页面开始使用
- <%@ taglib uri="/tags" prefix="date"%>
- <date:date value="${detail.sendTime}"/>
<%@ taglib uri="/tags" prefix="date"%>
<date:date value="${detail.sendTime}"/>
即可以将long型时间转化为yyyy-MM-dd HH:MM:ss类型
在自己定义的标签处理类中:pageContext.getOut().write(s) ,write方法可以接受两个参数int,String,
如果想在页面输出,只能用String类型参数的write方法。