java中使用freemarker生成静态页面文件(支持多语言):
FreeMarkerTest:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreeMarkerTest {
public static void main(String[] args) {
FreeMarkerTest test = new FreeMarkerTest();
test.getFile();
test.getFile(Locale.JAPAN);
}
public void getFile() {
Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setClassForTemplateLoading(this.getClass(),"/");
freemarkerCfg.setEncoding(Locale.getDefault(),"UTF-8");
Template template;
try {
template = freemarkerCfg.getTemplate("t.ftl");
template.setEncoding("UTF-8");
File htmlFile = new File("t.html");
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(htmlFile), "UTF-8"));
HashMap propMap = new HashMap();
propMap.put("user", "hermit");
template.process(propMap, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getFile(Locale loc) {
Configuration freemarkerCfg = new Configuration();
freemarkerCfg.setClassForTemplateLoading(this.getClass(),"/");
freemarkerCfg.setEncoding(Locale.getDefault(),"UTF-8");
Template template;
try {
template = freemarkerCfg.getTemplate("t.ftl",loc);
template.setEncoding("UTF-8");
File htmlFile = new File("t_"+loc.getLanguage()+"_"+loc.getCountry()+".html");
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(htmlFile), "UTF-8"));
HashMap propMap = new HashMap();
propMap.put("user", "hermit");
template.process(propMap, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
t.ftl
<html>
<head>
<title>Welcome!</title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
</head>
<body>
<h1>Welcome ${user}!</h1>
</body>
</html>
t_zh_CN.ftl
<html>
<head>
<title>欢迎!</title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
</head>
<body>
<h1>你好 ${user}!</h1>
</body>
</html>
freemarker支持多语言国际化,只要把模板名称安装资源文件的写法就可以了,也就是name_语言_国家地区.ftl
如果找不到对应的语言,就会用默认语言的模板。
顺便抱怨一下,freemarker对于空值的处理太霸道了,没有值你就写个空或者写KEY也可以啊,弄一堆出错信息在那。。。。。。。。。。。。。。