Jsp开发自定义标签,自定义标签将字符串转成指定的时间格式显示

时间:2023-03-09 03:09:21
Jsp开发自定义标签,自定义标签将字符串转成指定的时间格式显示

本例以将 字符串格式的时间转成指定的时间格式显示。

第一步、定义一个标签处理程序类,需要集成javax.servlet.jsp.tagext.TagSupport,代码如下:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar; import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
* 自定义的时间处理标签
*
*/
public class JSTLDateTag extends TagSupport {
/**
*
*/
private static final long serialVersionUID = -8683014812426654300L;
private String value;//对应jstl表达式中的value值
private String parttern;//对应表达式中的partern指定的时间格式 public int doStartTag() throws JspException {
String vv = String.valueOf(value);
long time = Long.valueOf(vv);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
SimpleDateFormat dateformat = new SimpleDateFormat(parttern);
String s = dateformat.format(c.getTime());
try {
pageContext.getOut().write(s);
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public String getParttern() {
return parttern;
} public void setParttern(String parttern) {
this.parttern = parttern;
} }

第二步、编写一个tld格式的文件。(格式类似于xml格式的文件)如下:dateformat.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlib-version>1.1</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>date</short-name> <tag>
<name>stringToDate</name>
<tag-class>com.xxx.JSTLDateTag</tag-class><!-- 刚才写的那个标签处理类-->
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>parttern</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

 第三步、在web.xml中加入配置,找到web.xml中的<jsp-config>节点加入<taglib>配置,代码如下:

    <jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tld/c.tld</taglib-location>
</taglib>
<!-- 自定义JSTL时间格式化 -->
<taglib>
<taglib-uri>/datetag</taglib-uri> <!-- 注意这里的 '/datetag',下面就要用到 -->
<taglib-location>/WEB-INF/tld/dateformat.tld</taglib-location>
</taglib>
</jsp-config>

第四步、在jsp页面中使用自定义标签,如下

<%@ taglib uri="/datetag" prefix="fmtDate"%>

<fmtDate:stringToDate parttern="yyyy-MM-dd HH:mm:ss" value="${hotContent.createDate}"></fmtDate:stringToDate>