Chủ Nhật, 6 tháng 3, 2011

xử lý template với Freemarker trong java

Chào các bạn, trong quá trình tìm hiểu mình có bắt gặp thư viện xử lý template hay,
Feemarker. Viết thử demo cái
package net.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Main {

public static final String DATA_PARAMETER = "data";

public Map parameters = new HashMap();

/**
* This exception handler is lenient when values are undefined. In that case nothing is printed or
* returned.
*/
public String getlabel() {
return "Demo Label";
}

public String getRootMenuOptions() {
return "Demo!";
}

public Configuration getNewConfiguration() {
final Configuration cfg = new Configuration();
cfg.setObjectWrapper(new DefaultObjectWrapper());

return cfg;
}

public String readFileAsString(File file) throws java.io.IOException {
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
f.read(buffer);
return new String(buffer);
}

public String readTemplateSourceFromClasspath(String path) {
try {

final File file = new File(path);
return readFileAsString(file);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}

public String generate() throws TemplateException {
if (getData() != null) {
parameters.put(DATA_PARAMETER, getData());
}

try {

Template tpl = new freemarker.template.Template("template", new StringReader(
readTemplateSourceFromClasspath("C:/Users/pc/workspace/Demo/src/net/net/demo.ftl")),
getNewConfiguration());
return processTemplate(tpl, parameters);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

}

public String processTemplate(freemarker.template.Template templateImplementation,
Map data) {
try {
final StringWriter output = new StringWriter();

templateImplementation.process(data, output);
return output.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (TemplateException e) {
// System.out.println("khong ton tai : " + e.toString());
return null;
}
}

public Object getData() {
return this;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Main demo = new Main();
// System.out.println("ga gag ");
try {
System.out.println("ket qua demo : " + demo.generate());
} catch (TemplateException e) {
// TODO Auto-generated catch block
// System.out.println("thu phat da " + e.toString());
}
}

}

- File demo.ftl: ${data.label},${data.rootMenuOptions}

Va ket qua la :
ket qua demo : title: Demo Label,Demo!