1.编写自定义标签类。
2. 创建taglib文件(.tld),编写标签声明。
第一步:
首先编写时间格式转换的方法:
public static String getDisplayTime(Date date){
Date nowDate=new Date();
Calendar oldCalendar=Calendar.getInstance();
Calendar nowCalendar=Calendar.getInstance();
oldCalendar.setTime(date);
nowCalendar.setTime(nowDate);
int day=getDaysBetween(oldCalendar,nowCalendar);
Long nowTime=nowDate.getTime();
Long oldTime=date.getTime();
Long time=nowTime-oldTime;
if(time>60*60*1000){
if(day==0){
return new SimpleDateFormat("HH:mm:ss").format(date);
}else if(day==1){
return "昨天"+new SimpleDateFormat("HH:mm:ss").format(date);
}else if(day==2){
return "前天"+new SimpleDateFormat("HH:mm:ss").format(date);
}else{
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
}else if(time<60*1000){
return "刚刚";
}else{
return (long)time/(60*1000)+"分钟前";
}
}
这段代码很简单,相信大家一看便懂了。
下面是距离当前时间天数的方法:
public class Times extends Component{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Times(ValueStack arg0) {
super(arg0);
}
@Override
public boolean start(Writer writer) {
boolean result = super.start(writer);
try {
java.util.Date date = (java.util.Date) findValue(name);
String str=DataTime.getDisplayTime(date);
writer.write(str);
} catch (IOException ex) {
Logger.getLogger(Pages.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
}
这里是写一个方法调用这个算法返回一个值
public class TimeTag extends ComponentTagSupport{
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public Component getBean(ValueStack arg0, HttpServletRequest arg1, HttpServletResponse arg2) {
return new Times(arg0);
}
//获得参数
protected void populateParams() {
super.populateParams();
Times pages = (Times)component;
pages.setName(name);
}
}
这里继承ComponentTagSupport类是为了获得标签中的属性值,并包装成Component对象。继承Component类是为了从Struts2中的ValueStack中获得相对应的值。
第二步:建立smallfish.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>2.2.3</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>smallfish</short-name>
<uri>/jzy</uri>
<display-name>"smallfish Tags"</display-name>
<tag>
<name>times</name>
<tag-class>com.common.tag.TimeTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>