配置文件freemarker.properties
#在消费者存放页面的地方的地址
out_print_path=E:/java/IdeaProjects/CZJK/health_parent/health_mobile/src/main/webapp/pages
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--创建freemarker对象-->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="defaultEncoding" value="utf-8"></property>
<property name="templateLoaderPath" value="/WEB-INF/pages/"></property>
</bean>
<!--加载配置文件-->
<context:property-placeholder location="classpath:freemarker.properties"></context:property-placeholder>
</beans>
对象的注入
@Autowired
private FreeMarkerConfigurer markerConfigurer;//注入对象
@Value("${out_print_path}")
private String path;//从配置文件注入值
简单应用
public void getSetMealHtml(){
//通过FreeMarkerConfigurer来得到一个Configuration
Configuration configuration = markerConfigurer.getConfiguration();
BufferedWriter bf=null;
try {
//得到模板名称
Template template = configuration.getTemplate("setmeal.ftl");
//设置数据
Map map=new HashMap();
//查到所有的数据
List<Setmeal> setmealList = findAll();
//发送给前端
map.put("setmealList",setmealList);
//设置流并设置字符集
bf=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path+"/setmeal.html"),"utf-8"));
//执行生成html文件
template.process(map,bf);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}finally {
try {
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端页面
<ul class="list">
<li class="list-item">
<#list setmealList! as setmeal>
<a class="link-page" href="setmeal_detail.html?id=${setmeal.id}">
<img class="img-object f-left" src="http://q8re0dlhm.bkt.clouddn.com/${setmeal.img}" alt="">
<div class="item-body">
<h4 class="ellipsis item-title">${setmeal.name!}</h4>
<p class="ellipsis-more item-desc">${setmeal.remark!}</p>
<p class="item-keywords">
<span>
<#if setmeal.sex=='0'>
性别不限
<#else>
<#if setmeal.sex=='1'>
男
<#else>
女
</#if>
</#if>
</span>
<span>${setmeal.age!}</span>
</p>
</div>
</a>
</#list>
</li>
</ul>