您的位置:首页 > 其它

如何在项目里面使用freemarker实现页面缓存(三)

2016-10-20 16:14 525 查看
1.环境配置:在这里我就不说了,上面两篇有如何配置freemarker

2.在项目里面你运用freemarker需要在项目里面创建一个模板文件夹,在web-inf下面创建一个ftl文件夹

3.由于通过freemarker将模板页面转化为html页面,前台访问直接跳页面就行了,所以不能把生成的html文件放入web-inf文件夹下面,在webapp下创建一个文件夹命名html

4.写service方法

4.1由于该方法需要交给spring统一管理,所以需要注入到spring里面

4.2创建一个接口StaticPageService

import java.util.Map;

public interface StaticPageService {

public void productIndex(Map<String, Object> root,Integer id);

}


4.3创建接口的实现类

public class StaticPageServiceImpl implements StaticPageService,ServletContextAware{

private Configuration configuration;

public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
this.configuration = freeMarkerConfigurer.getConfiguration();
}
//静态化方法
public void productIndex(Map<String, Object> root,Integer id){
//输出流 从内存中写入磁盘
Writer out=null;
//创建模板
try {
//读入utf-8的数据到内存里面
Template template = configuration.getTemplate("productDetail.html");
String path=getPath("/html/product/"+id+".html");
File file=new File(path);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
out=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
//模板对象处理
template.process(root, out);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放io流
if (out!=null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

}
//获取上下文路径
public String getPath(String name){

return servletContext.getRealPath(name);
}
private ServletContext servletContext;

public void setServletContext(ServletContext servletContext) {
this.servletContext=servletContext;

}

}


注意:由于要获取模板文件夹的路径

需要实现ServletContextAware接口重写里面的setServletContext方法,本service是使用set方式手动注入的。

root为要填充页面的数据。

4.4在spring配置文件里面注入

<!-- 配置freemarker -->
<bean id="staticPageService" class="cn.itcast.core.service.staticpage.StaticPageServiceImpl">
<property name="freeMarkerConfigurer">
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- 设置模板路径 -->
<property name="templateLoaderPath" value="/WEB-INF/ftl/"></property>
<!-- 设置控制模板为utf-8 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
</property>
</bean>


注意:这两个参数必须传

4.5 就是模板了,要将所有的标签根据freemarker的语法转化正确,由于free marker支持el表达式就不用转化

例如:

<#list skus as sku>
if("${sku.colorId}"==colorId && size=='${sku.size}'){
//赋值
$("#price").html("¥"+'${sku.skuPrice}');
$("#mprice").html("¥"+'${sku.marketPrice}');
$("#free").html('${sku.deliveFee}');
$("#stock").html('${sku.stockInventory}');
skuId='${sku.id}';
buyLimit='${sku.skuUpperLimit}';
}
</#list>


启动程序看相应文件夹生成相应的html文件了没有。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐