惯例:
我是温浩然:
自定义标签分为这么几部分,
1、tld文件,标签文件,主要定义标签的属性,标签的实现类等。
2、标签实现类,Java文件,实现标签的功能。
3、标签引用,在JSP中,对标签进行引用。
下面开始贴代码,首先是tld标签文件。
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>tu</short-name>
<uri>http://www.erzao.org/taglib</uri>
<tag>
<name>formatdate</name>
<tag-class>com.tujia.core.util.FormatDate</tag-class>
<body-content>empty</body-content>
<attribute>
<name>date</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>time</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>contains</name>
<tag-class>com.tujia.core.Contains</tag-class>
<body-content>empty</body-content>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>list</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>obj</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
这里面有顶部引用文件,
和标签的版本信息。
<tlib-version>1.0</tlib-version>
<short-name>tu</short-name>
<uri>http://www.erzao.org/taglib</uri>
以及标签体,等,就是定义标签的实现类和标签具体的属性等。
下面是标签的实现类。
package com.tujia.core.util;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.joda.time.DateTime;
public class FormatDate extends SimpleTagSupport {
private Date date;
private long time;
public void doTag() throws JspException{
try {
DateTime d = null;
if(this.date != null){
d = new DateTime(this.date);
}else if(this.time>0){
Date date = new Date(this.time);
d = new DateTime(date);
}
if(d == null)return;
getJspContext().getOut().print(d.getYear()+"-"+d.getMonthOfYear()
+"-"+d.getDayOfMonth()
);
} catch (Exception e) {
}
}
public void setDate(Date date) {
this.date = date;
}
public void setTime(long time) {
this.time = time;
}
}
这个也挺简单的。
再下面就是JSP中的引用了。更简单。
<tu:formatdate time="${user.birthTime}" />
OK,这就可以了