写道
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.ext.beans.ResourceBundleModel;
import freemarker.ext.beans.BeansWrapper;
import java.io.StringWriter;
import java.util.Locale;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.Map;
/**
* @author jm
*/
public class FreeMarkerTest {
public static void main(String[] args) {
FreeMarkerTest test = new FreeMarkerTest();
test.sayHello("hermit", Locale.FRENCH);
test.sayHello("hermit", Locale.ENGLISH);
}
public void sayHello(String name, Locale locale) {
Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setClassForTemplateLoading(this.getClass(), "/");
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
Template template;
Locale.setDefault(Locale.ENGLISH);
try {
template = freemarkerCfg.getTemplate("hello.ftl");
template.setEncoding("UTF-8");
Map<String,Object> root = new HashMap<String,Object>();
root.put("user", name);
ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("message", locale);
ResourceBundleModel rsbm = new ResourceBundleModel(RESOURCE_BUNDLE, new BeansWrapper());
root.put("bundle", rsbm);
StringWriter writer = new StringWriter();
template.process(root, writer);
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}