freemaker和spring整合的配置文件:
<!-- 手动实现化 静态化实现类 -->
<bean id="staticPageService" class="com.core.service.StaticPageServiceImpl">
<property name="freeMarkerConfigurer">
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- 设置模板所在目录的相对路径 -->
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
静态化模板定义程序:
public class StaticPageServiceImpl implements StaticPageService,ServletContextAware {
private Configuration conf;
public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
this.conf = freeMarkerConfigurer.getConfiguration();
}
//静态化程序
public void index(Map<String,Object> root,Long id) {
//全路径
String path = getPath("/html/product/" + id + ".html");
File f = new File(path);
File parentFile = f.getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
//模板
Writer out = null;
try {
//读 UTF-8
Template template = conf.getTemplate("product.html");
//写 UTF-8
out = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
template.process(root, out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(null != out){
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//全路径
public String getPath(String path){
return servletContext.getRealPath(path);
}
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
// TODO Auto-generated method stub
this.servletContext = servletContext;
}
}
修改jsp页面为html页面,用freemaker标签替换c标签
静态化使用:
Map<String,Object> root = new HashMap<>();//把需要传递给页面的参数放到map中
// 通过商品Id 查询商品对象
Product p = cmsService.selectProductById(id);
// 通过商品ID Sku结果集 (Sku对象中颜色对象)
List<Sku> skus = cmsService.selectSkuListByProductId(id);
root.put("product", p);
root.put("skus", skus);
Set<Color> colors = new HashSet<Color>();
for (Sku sku : skus) {
colors.add(sku.getColor());
}
root.put("colors", colors);
staticPageService.index(root, id);
}