jspカスタムラベルインスタンス

5292 ワード

ステップ3:
一、WEB-INFの下にtldsというフォルダを作成し、formatTimeのようなtldファイルを再構築する.tld、内容は:
 
  

br>"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

1.0
1.1
ntuc

formatTimeAsString
com.ufinity.taglibTest.FormatTimeTag
empty

timestamp


format


showTH


style




二、classを建設し、内容は以下の通りである.
 
  
package com.ufinity.taglibTest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Description of the class
*
* @author Wangqy
* @version 1.0
* @since 2009-8-25
*/
public class FormatTimeTag extends TagSupport {
/**
* serialVersionUID long
*/
private static final long serialVersionUID = 8757501937718830491L;
private String timestamp;
private String format;
private String showTH;
private String style;
public int doEndTag()
{
try
{
String info = this.convertDateTime(timestamp, format, Boolean.parseBoolean(showTH), style);
pageContext.getOut().println(info);
}
catch (IOException e) {
}
return EVAL_PAGE;
}
private String convertDateTime(String dateTime, String formater, boolean showTH, String caseStyle) {
String timePosted = null;
SimpleDateFormat dateFm = null;
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date formatTime = null;
try {
formatTime = format.parse(dateTime);
} catch (ParseException e) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(formatTime);
if (showTH) {
int day = calendar.get(Calendar.DAY_OF_MONTH);
String daySuffix = "th";
if ((day % 10) == 1) {
daySuffix = ((day / 10) == 1) ? "th" : "st";
} else if ((day % 10) == 2) {
daySuffix = (day == 12) ? "th" : "nd";
} else if ((day % 10) == 3) {
daySuffix = (day == 13) ? "th" : "rd";
}
formater = formater.substring(0, formater.indexOf(" ")) + "'"
+ daySuffix + "'"
+ formater.substring(formater.indexOf(" "));
dateFm = new SimpleDateFormat(formater, Locale.ENGLISH);
} else {
dateFm = new SimpleDateFormat(formater, Locale.ENGLISH);
}
timePosted = dateFm.format(formatTime);
if (caseStyle.equals("Upper")) {
timePosted = timePosted.toUpperCase();
} else if (caseStyle.equals("Lower")) {
timePosted = timePosted.toLowerCase();
}
return timePosted;
}
public void setFormat(String format) {
this.format = format;
}
public void setShowTH(String showTH) {
this.showTH = showTH;
}
public void setStyle(String style) {
this.style = style;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}

三、jspページのテストを作成する.
 
  









“20090403132233”


format:dd MMMM yyyy showTH:true style:Upper :

format:dd MMMM yyyy showTH:true style:Lower :

format:dd MMMM yyyy showTH:false style:Upper :

format:dd MMMM yyyy showTH:true style:"" :




OKです.ここでtimestampは所定の値であり、${}タグで動的に取り出す場合はtldファイルの
 
  

timestamp


次のように変更
 
  

timestamp
true