一.在maven环境下使用流程
1.导入坐标
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2.创建模板文件(一般是html)
1、文本,直接输出的部分
2、注释,即<#–…-->格式不会输出
3、插值(Interpolation):即${…}部分,
将使用数据模型中的部分替代输出
4、FTL指令:FreeMarker指令,和HTML标记类似,名字前加#予以
区分,不会输出
Freemarker的模板文件后缀可以任意,一般建议为ftl
<html>
<head>
<meta charset="utf-8">
<title>Freemarker入门</title>
</head>
<body>
<#--我只是一个注释,我不会有任何输出 -->
${name}你好,${message}
</body>
</html>
3.生成文件
public static void main(String[] args) throws Exception{
//1.创建配置类
Configuration configuration=new Configuration(Configuration.getVersion());
//2.设置模板所在的目录
configuration.setDirectoryForTemplateLoading(new File("D:\\ftl"));
//3.设置字符集
configuration.setDefaultEncoding("utf-8");
//4.加载模板
Template template = configuration.getTemplate("test.ftl");
//5.创建数据模型
Map map=new HashMap(); map.put("name", "张三"); map.put("message", "欢迎来到xxxx!");
//6.创建Writer对象
Writer out =new FileWriter(new File("d:\\test.html"));
//7.输出
template.process(map, out);
//8.关闭Writer对象
out.close(); }
4.在项目中的使用
在服务提供者的WEB-IF下面配置模板,实现类里生成静态页面
provider工程中创建属性文件freemarker.properties,封装out_put_path
@Value("${out_put_path}")
private String outPutPath;
public void add(Setmeal setmeal, Integer[] checkGroupIds) {
setMealDao.add ( setmeal );
if (checkGroupIds.length > 0 && checkGroupIds != null) {
Map<String, Integer> map = new HashMap<> ();
for (Integer checkGroupId : checkGroupIds) {
// Map<String, Integer> map = new HashMap<> ();
map.put ( "setmeal_id", setmeal.getId () );
map.put ( "checkgroup_id", checkGroupId );
setMealDao.setSetMealAndCheckGroup ( map );
}
}
//把图片名称加入redis缓存
jedisPool.getResource ().sadd ( RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg () );
generateMobileStaticHtml ();
}
//生成静态页面
public void generateMobileStaticHtml() {
List<Setmeal> setmealList = setMealDao.findAll ();
generateMobileSetmealListHtml ( setmealList );
generateMobileSetmealDetailHtml ( setmealList );
}
//生成套餐列表静态页面
public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
Map map = new HashMap ();
map.put ( "setmealList", setmealList );
generteHtml ( "mobile_setmeal.ftl", "m_setmeal.html", map );
}
//生成套餐详情页面
public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
for (Setmeal setmeal : setmealList) {
Map map = new HashMap ();
map.put ( "setmeal", setMealDao.findById ( setmeal.getId () ) );
generteHtml ( "mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId () + ".html", map );
}
}
//通用方法,加载模板,嵌套数据
public void generteHtml(String templateName, String htmlPageName, Map map) {
Configuration configuration = freeMarkerConfigurer.getConfiguration ();
Writer out = null;
try {
Template template = configuration.getTemplate ( templateName );
out = new FileWriter ( new File ( outPutPath + htmlPageName ) );
template.process ( map, out );
} catch (Exception e) {
e.printStackTrace ();
} finally {
try {
if (out != null) {
out.close ();
}
} catch (IOException e) {
e.printStackTrace ();
}
}
}