非诚勿扰李欣:jsp高手请帮小弟一个忙?

来源:百度文库 编辑:神马品牌网 时间:2024/05/03 05:06:41
我是个新手,想学做自定义标签?那位高手能做个例子演示一下?小弟比较愚笨,如果加上图片,不甚感谢!
请大家关注,谢谢

在我们的平台中,有一个时间格式的问题,虽然有了很多现成的标签可以使用,比如说在JSTL中有,struts中有可以用,但是都不与我们现在的平台相互兼容,俺今天想了一下,利用自定义的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文件 如下:

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2/EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd" >

1.0
1.2
site-utils
/WEB-INF/tr.tld

dataTag
com.tr1997.tag.DateTag

display
true
false

接下来就在web.xml文件引用此标签。

/WEB-INF/tr.tld
/WEB-INF/tr.tld

最后就是如何在jsp页面去引用了。

先引用在jsp头部。

在你在使用的地方,用

2004-01-01 00:00:00.0

结果为2004-01-01

2004-01-01 00:00:00.0

结果为2004-01-01 00:00:00.0

这样标签算是完成了。

在tomcat4.0 ,5.0 测试通过。