1.首先从官方网站下载最新版本,把jar(Velicity的主要包和相关的工具包)加入到项目中。
2.后台代码实现如下
2.velocity相关指令
2.后台代码实现如下
File file = new File("generalpage.htm");
Writer writer = new FileWriter(file);//生成的静态页面
String encoding = "UTF-8";
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=" + encoding);
VelocityEngine ve = null;
try {
Properties properties = null;
if (properties == null) {
properties = new Properties();
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,
request.getSession().getServletContext().getRealPath("/") + "WEB-INF/vm");//模板存放的路径
properties.setProperty(Velocity.ENCODING_DEFAULT, encoding);
properties.setProperty(Velocity.INPUT_ENCODING, encoding);
properties.setProperty(Velocity.OUTPUT_ENCODING, encoding);
}
ve = new VelocityEngine();
ve.init(properties);
} catch (Exception e) {
System.out.println("Problem initializing Velocity : " + e);
return;
}
VelocityContext vcontext = new VelocityContext();
DataFactory df = new DataFactory();
vcontext.put("news", df.getItems(c, "1", community_id, 6));
DateTool datetool = new DateTool();//时间工具的使用
vcontext.put("date", datetool);
DisplayTool displayTool = new DisplayTool();//显示处理工具的使用
vcontext.put("display", displayTool);
vcontext.put("contexpath", request.getContextPath());
try {
String templateName = UniversityHomeTemplate.findById(c, template_id).getTemplateName();//读取模板的文件名
ve.mergeTemplate(templateName, encoding, vcontext, writer);
writer.close();
} catch (Exception e) {
System.out.println("Problem merging template : " + e);
writer.close();
e.printStackTrace();
}
2.velocity相关指令
#foreach( $train in $trains )
$display.truncate($train.title, 12)</a>
$date.format('yyyy-M-d',$train.created_date)
#end
#if($news.size() > 0)
$display.truncate($news.get(0).content, 70)
#end