---
title: "Velocity + Spring定时器 生成静态页面"
author: "zgzdlm"
date: "2012-10-22T11:27:41Z"
tags: []
categories: ["Web前端"]
slug: "velocity-spring"
draft: false
lastmod: "2012-10-22T11:27:24Z"
id: 1702850
url: "https://zgzdlm.iteye.com/blog/1702850"
---

最近做项目需要将首页静态化，于是着手了下velocity，成功将首页静态化。 首先需要下载 velocity-dep.jar 在附件中我上传了 velocity需要配置如下 velocity.property 日志生成路径 runtime.log = velocity.log 乱码解决 input.encoding=GBK output.encoding=GBK 指定vm模板路径 绝对所在路径(如我的vm模板放在src下 编译后就在一下目录了) file.resource.loader.path = X://workspace//test//web//WEB-INF//classes spring定时器 \[code="java"]public class ToHTMLServiceImp implements ToHTMLService{ // 稿件点击排行 private List articlelist = new ArrayList(); public void toHtml() { //执行查询的方法 articlelist = 查询方法list //使用vm模板静态化 读取配置文件 VelocityEngine ve = new VelocityEngine(); ve.init("X:\\\\workspace\\\\test\\\\src\\\\velocity.properties"); VelocityContext context = new VelocityContext(); //路径跟前面设置的path相对应 Template template = ve.getTemplate("mytemplate.vm"); //将获得的对象放入Velocity的环境上下文中方便取用 context.put("articleListMap", articleListMap); //将模板生成到指定位置 我生成的名字叫home.html File savefile = new File("X:\\\\workspace\\\\test\\\\web\\\\site\\\\home\\\\home.html"); if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs(); FileOutputStream outstream = new FileOutputStream(savefile); OutputStreamWriter writer = new OutputStreamWriter(outstream,"GBK"); BufferedWriter bufferWriter = new BufferedWriter(writer); template.merge(context, bufferWriter); bufferWriter.flush(); outstream.close(); bufferWriter.close(); }catch( Exception e ){ e.printStackTrace(); } }\[/code] jsp页面包含html &lt;%@include file="home\_head.jsp" %&gt; &lt;%@include file="home\_foot.jsp" %&gt; spring定时器相关配置 toHtml 0 600000 contextConfigLocation /WEB-INF/classes/config/site/site-time-task.xml org.springframework.web.context.ContextLoaderListener vm标签语法 我贴几个我为了方便贴在记事本里的草稿 应该很容易理解 所以不解释了:) $element.sid #set ($i=0) #foreach($element in $pictureList) #set($i=$i+1) $element.getStringFormat($element.name,22) $element.fileDate #foreach($element in $articleListMap.get("test")) #foreach($element in $zhuantiList) #if($velocityCount &lt; 4) #end $element.getStringDate($element.fileDate,5,10)