SAStrutsプロジェクトでFreeMarkerをちょっぴり簡単に使ってみる
前のブログからの移行記事です。
汎用テンプレートエンジンとしてはFreeMarker以外にもVelocityとかもありますが、S2JDBC-genでもFreeMarkerを使っているということもあり、ここではFreeMarkerを使っていきたいと思います。
テンプレートファイルはクラスパス上に"ftl"というフォルダーを作成し、その中に置くようにします。
FreeMarkerを使うための記述は、通常ならこんな感じでしょう。
Configuration cfg = new Configuration(); cfg.setTemplateLoader(new ClassTemplateLoader(this.getClass(),"/ftl")); // publicフィールド対応 BeansWrapper bw = new BeansWrapper(); bw.setExposeFields(true); cfg.setObjectWrapper(bw); // 文字コードは"UTF-8" cfg.setEncoding(Locale.JAPANESE,"UTF-8"); Template template = cfg.getTemplate("sample.ftl"); HashMap lHashMap = new HashMap(); lHashMap.put("data",data); StringWriter writer = new StringWriter(); template.process(lHashMap,writer); writer.flush();
これだと、Configuration生成〜設定の部分を毎回記述するのが面倒なので、DIコンテナで管理するようにします。
<component name="ftlConfiguration" class="freemarker.template.Configuration"> <property name="templateLoader"> new freemarker.cache.ClassTemplateLoader(@org.seasar.framework.container.S2Container@class,"/ftl/") </property> <property name="objectWrapper"> <component class="freemarker.ext.beans.BeansWrapper"> <property name="exposeFields">true</property> </component> </property> <initMethod name="setEncoding"> <arg>@java.util.Locale@JAPANESE</arg> <arg>"UTF-8"</arg> </initMethod> </component>
Freemarkerを使う処理はFreemarkerLogicにまとめることにします。
import java.io.*; import java.util.*; import javax.annotation.*; import jp.co.lte.saspractice.entity.*; import freemarker.template.*; /** * * <P> * * </P> * 作成日:2009/10/14 * @author Rita */ public class FreemarkerLogic { @Resource protected Configuration ftlConfiguration; }
例えば従業員1件分のデータをテキスト出力するような例。
EmployeeData.ftl
■■従業員情報■■ 従業員番号: ${employee.employeeNo} 氏名: ${employee.name} 年齢: ${employee.age!} メールアドレス: ${employee.mailAddress!} 誕生日: ${employee.birthday!}
FreemarkerLogic
public String writeEmployeeData(Employee employee)throws Exception { Template template = ftlConfiguration.getTemplate("EmployeeData.ftl"); HashMap lHashMap = new HashMap(); lHashMap.put("employee",employee); StringWriter writer = new StringWriter(); template.process(lHashMap,writer); writer.flush(); return writer.toString(); }
従業員一覧データをテキスト出力する場合はこんな感じ。
EmployeeList.ftl
■■従業員一覧■■ 従業員番号 名前 年齢 誕生日 メールアドレス <#list employeeList as employee> ${employee.employeeNo} ${employee.name} ${employee.age!} ${employee.birthday!"未登録"} ${employee.mailAddress!} </#list>
FreemarkerLogic
public String writeEmployeeList(List<Employee> employeeList)throws Exception { Template template = ftlConfiguration.getTemplate("EmployeeList.ftl"); HashMap lHashMap = new HashMap(); lHashMap.put("employeeList",employeeList); StringWriter writer = new StringWriter(); template.process(lHashMap,writer); writer.flush(); return writer.toString(); }
FreemarkerLogicのメソッドは、テンプレートに埋め込むべきデータをパラメーターで受け取り、完成した文字列を返すだけの処理を行うようにしています。
FreemarkerLogicの役割が明確になり、メソッドの汎用性が増します。
ConfigurationをDIコンテナで管理しているので、記述も簡単です。