首先,得导入jar包 jsp-api-2.2-sources.jar
(如果你的项目中使用了maven可以在pom.xml文件中添加
<dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency>
jar文件引用。
)
第二步,定义一个用来实现标签功能的java类,例如:DateConvert.java
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
* 数据类型转换
* @author LiDuanqiang
*
*/
@SuppressWarnings("serial")
public class DateConvert extends TagSupport{
private String longTime;
@Override
public int doStartTag() throws JspException {
long l = 0l;
if (longTime!=null&&!longTime.equals("")) {
l = Long.parseLong(longTime);
}
Date date = new Date(l);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String targetTime = format.format(date);
try {
super.pageContext.getOut().write(targetTime);
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
//setter and getter
public void setLongTime(String longTime) {
this.longTime = longTime;
}
}
第三步,可在WEB-INF目录下定义一个*.tld文件,例如dateConvert.tld:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>ct</short-name>
<uri>/dateConvert</uri>
<tag>
<name>longStr</name>
<tag-class>org.up.snapshot.utils.DateConvert</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>longTime</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
第四步,在web.xml文件中引用你的*.tld文件:
<taglib> <taglib-uri>/dateConvert</taglib-uri> <taglib-location>dateConvert.tld</taglib-location> </taglib> <welcome-file-list> <welcome-file>dateConvert.jsp</welcome-file> </welcome-file-list>
第五步,在你的页面引入自定义标签库进行使用,例如:dateConvert.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="/dateConvert" prefix="ct"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>数据类型转换</title> </head> <body> <ct:longStr longTime="1314842011312"></ct:longStr> </body> </html>
以上代码实现的是将长整型的数据通过自定义标签转换成指定日期格式进行输出。当然,大家可以定义功能更加强大的java类来实现你的标签功能。
本文介绍如何创建自定义JSP标签以实现长整型时间戳到指定日期格式的转换。首先需要导入必要的jar包,接着定义一个Java类处理标签功能,再通过*.tld文件描述标签,并在web.xml中引用tld文件,最后在JSP页面使用自定义标签。
167

被折叠的 条评论
为什么被折叠?



