Tapstry5.0.4 中自定translator(Date爲例)


信息來源 http://tapestrying.group.javaeye.com/group/topic/1361
本文主要是介紹如何自定義 translator。
首先需要了解translator的作用 :

translator用來服務端和客戶端值的轉換
客戶端顯示永遠都是String,而傳到服務器端我們希望是其他的類型,這是就要用到translator了.
由於當前T5提供了名爲number,double,string,integer的tanslator,
假設你定義了名爲date的translator,html template看起來應該像這樣:
<input t:type="TextField" t:id="date" t:translate="translate:date" t:value="date" size="30" />

注意t:translate="translate:date"這個屬性,這個date就需要我們自己定義 ,定義如下:

package org.opend.bogo.translator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.tapestry.Translator;
import org.apache.tapestry.ValidationException;
import org.apache.tapestry.ioc.Messages;
import org.apache.tapestry.ioc.internal.util.InternalUtils;

public class DateTranslator implements Translator<Date>
{

public Date parseClient(String clientValue, Messages messages) throws ValidationException
{
if (InternalUtils.isBlank(clientValue))
return null;

try
{
SimpleDateFormat format 
= new SimpleDateFormat("MM/dd/yyyy");
Date date 
= format.parse(clientValue);
return date;
}

catch (ParseException ex)
{
throw new ValidationException(messages.format("number-format-exception", clientValue));
}

}


/**
* Converts null to the blank string, non-null to a string representation.
*/

public String toClient(Date value)
{
SimpleDateFormat format 
= new SimpleDateFormat("MM/dd/yyyy");
return value == null ? "" : format.format(value);
}

}


定義完轉換類後需要註冊你的 translator

定義MyAppModule,登記這個Translator

package org.opend.bogo.modules;

import java.io.IOException;
import java.util.Date;
import org.apache.tapestry.Translator;
import org.opend.bogo.translator.DateTranslator;

.......
public class MyAppModule {
public static void contributeTranslatorDefaultSource(
MappedConfiguration
<Class, Translator> configuration) {
configuration.add(Date.
classnew DateTranslator());
}


public static void contributeTranslatorSource(
MappedConfiguration
<String, Translator> configuration) {
configuration.add(
"date"new DateTranslator());
}

.....
}


在classes/META-INF/MANIFEST.MF啓動這個Module
Manifest-Version: 1.0
Tapestry-Module-Classes: org.opend.bogo.modules.MyAppModule

OK,再試一次,看看頁面OK了吧?


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章