なんじゃくにっき

プログラミングの話題中心。

T2Framework の View 部分にFreeMarker を使う(2) Navigation自作編(I)

一昨日のエントリT2Frameworkコミッタのid:shot6さんにコメントを頂いたので
自分でもNavigation拡張を行ってみた。
 


FreeMarker用拡張Navigationクラス
package test.navigation;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.t2framework.commons.util.Logger;
import org.t2framework.t2.contexts.WebContext;
import org.t2framework.t2.navigation.Forward;
import org.t2framework.t2.navigation.WebNavigation;

import freemarker.template.Template;

public class FTLNavigation extends WebNavigation {

@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(Forward.class);

protected Template template;
protected Map<String, Object> root = new HashMap<String, Object>();

public FTLNavigation(Template template) {
this.template = template;
}

public static FTLNavigation getNavigation(Template template) {
return new FTLNavigation(template);
}

public Template getTemplate(){
return this.template;
}

public FTLNavigation setEncoding(String encoding){
this.template.setEncoding(encoding);
return this;
}

public String getEncoding(){
return this.template.getEncoding();
}

public FTLNavigation setRoot(Map<String, Object> root) {
this.root = root;
return this;
}

public FTLNavigation put(String key, Object value) {
this.root.put(key, value);
return this;
}

@Override
public void execute(WebContext context) throws Exception {
String encoding = template.getEncoding();
if (encoding != null)
context.getResponse().setContentType("text/html; charset=" + encoding);

PrintWriter out = context.getResponse().getNativeResource().getWriter();
template.process(root, out);
}
}

 

Pageクラス
package test.page;
import org.t2framework.commons.annotation.composite.RequestScope;
import org.t2framework.commons.util.Logger;
import org.t2framework.t2.annotation.core.Default;
import org.t2framework.t2.annotation.core.Page;
import org.t2framework.t2.annotation.core.RequestParam;
import org.t2framework.t2.spi.Navigation;

import test.navigation.FTLNavigation;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

@Page("/view")
@RequestScope
public class ViewPage {
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(ViewPage.class);
@Default
public Navigation view(@RequestParam("p") String p) throws Exception{

Configuration config = new Configuration();
config.setObjectWrapper(new DefaultObjectWrapper());
Template template = config.getTemplate("WEB-INF/html/view.html");

return FTLNavigation.getNavigation(template)
.setEncoding("utf-8")
.put("message", p);
}
}

 
結構簡単に拡張できるのでいい感じ。
Navigationクラスの名前に困った・・
しっくりくるのが思いつかない。
 
追記:
Printwriterのcloseはコンテナに任せたほうがいいので修正。