使用velocity模版制作工具的步骤
velocity使用帮助
velocity是一个很好的制作模版的工具,特别适合于网站生成大量的静态html页面,这样可以减少对于数据库访问造成的资源消耗。
在这里不对velocity的使用作说明,这些在网上有很多资料,只想根据自己项目中遇到的问题作出一些记录,希望能给大家提供帮助:
在velocity中需要使用到模版,模版的存放路径是通过配置文件*.properties来设置的;我们可以在这里使用绝对路径也可以使用
相对路径,如我的项目中jsp页面放在d:/tomcat/webapps/BjLife下,模版放在d:/vm目录下,这样properties文件的模版路径 部分可以这样写:file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader file.resource.loader.path = d:/vm file.resource.loader.cache = false file.resource.loader.modificationCheckInterval = 2 在相应的程序中你可以指定模版文件路径: 完成jsp代码如下:<%@ page import="java.io.*" %>
<%@ page import="java.io.StringWriter" %> <%@ page import="org.apache.velocity.app.VelocityEngine" %> <%@ page import="org.apache.velocity.app.Velocity" %> <%@ page import="org.apache.velocity.Template" %> <%@ page import="org.apache.velocity.VelocityContext" %> <%@ page import="com.bjlife.db.*"%> <%@ page import="com.bjlife.util.*"%> <%@ page import="java.sql.*"%> <%@ page import="java.net.*"%> <%@ page import="java.util.Properties"%><%
//数据库连接 Connection conTmp = null; Statement stmtTmp = null; ResultSet rstTmp = null; String filepath="d://"; String vmpath="."; FileReader fr=null; FileWriter fw=null; DBFactory dbFactory=new DBFactory(); StringUtils sutils=new StringUtils();Properties p = new Properties();//通过Properties对象设置配置信息
Template template = null; try{ p.setProperty("file.resource.loader.path", "d:/vm"); //设置velocity的输入输出编码转换 p.setProperty("output.encoding", "gb2312"); p.setProperty("input.encoding", "iso-8859-1");//输入的编码 Velocity.init( p ); //取得模版文件 template = Velocity.getTemplate("test.vm"); } catch(Exception e) { System.out.println(e.toString()); }try {
conTmp = dbFactory.getConnection(); stmtTmp = conTmp.createStatement(); String Menusql="select * from test"; rstTmp = stmtTmp.executeQuery(Menusql); while (rstTmp.next()) { VelocityContext context=new VelocityContext(); String menutype=rstTmp.getString("menutype"); context.put("title",menutype); String menuname=rstTmp.getString("menuname"); menuname = new String(menuname.getBytes("GBK"), "ISO-8859-1"); context.put("menuname",menuname); String menuicon=rstTmp.getString("menuicon"); context.put("menuicon",menuicon); StringWriter writer=new StringWriter(); template.merge(context,writer); fw=new FileWriter(filepath +rstTmp.getString("menu_dm")+".html");//建立FileWriter对象,并实例化fw fw.write(writer.toString()); fw.close(); } } catch (SQLException exTmp) { exTmp.printStackTrace(); System.out.println("数据插入数据库出现错误!"); } finally{ try { stmtTmp.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("数据插入数据库出现错误!"); } try { conTmp.close(); }catch (Exception e) { e.printStackTrace(); System.out.println("数据插入数据库出现错误!"); } }%>