在我们的平台中,有一个时间格式的问题,虽然有了很多现成的标签可以使用,比如说在JSTL中有<fmt>,struts中有<bean:write>可以用,但是都不与我们现在的平台相互兼容,俺今天想了一下,利用自定义的TAG来在实现他。
首先,定义的一个bean 名为Date类,如下:
/*
* Created on 2005-1-12
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.tr1997.tag;
/**
* @author zhengjintian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Date {
public Date(){
}
public String dateToStr(Object obj,boolean b){
String str = obj.toString();
if(b&&str.length()>10){
str = str.substring(0,10);
}
return (str);
}
public static void main(String[] args) {
}
}
然后定义一个DateTag类,如下:
/*
* Created on 2005-1-12
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.tr1997.tag;
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
* @author zhengjintian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class DateTag extends BodyTagSupport {
public boolean display ;
/**
* @return Returns the display.
*/
public boolean isDisplay() {
return display;
}
/**
* @param display The display to set.
*/
public void setDisplay(boolean display) {
this.display = display;
}
public int doEndTag() throws JspTagException {
String str = "";
try {
BodyContent lbc_bodycurrent = this.getBodyContent();
if (lbc_bodycurrent != null) {
String ls_message = lbc_bodycurrent.getString();
Date dt = new Date();
str = dt.dateToStr(ls_message,display);
pageContext.getOut().write(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return EVAL_PAGE;
}
}
再来,写一个tr.tld文件 如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!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>site-utils</short-name>
<uri>/WEB-INF/tr.tld</uri>
<tag>
<name>dataTag</name>
<tag-class>com.tr1997.tag.DateTag</tag-class>
<attribute>
<name>display</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
接下来就在web.xml文件引用此标签。
<taglib>
<taglib-uri>/WEB-INF/tr.tld</taglib-uri>
<taglib-location>/WEB-INF/tr.tld</taglib-location>
</taglib>
最后就是如何在jsp页面去引用了。
<%@ taglib uri="/WEB-INF/tr.tld" prefix="tr1997" %>先引用在jsp头部。
在你在使用的地方,用
<tr1997:dataTag display="true">2004-01-01 00:00:00.0</tr1997:dataTag>
结果为2004-01-01
<tr1997:dataTag display="false">2004-01-01 00:00:00.0</tr1997:dataTag>
结果为2004-01-01 00:00:00.0
这样标签算是完成了。
在tomcat4.0 ,5.0 测试通过。