初识velocity
来源:互联网 发布:淘宝网商品销售方式 编辑:程序博客网 时间:2024/04/28 06:24
首先,工欲善其事必先利其器,要利其器必须要找到合适的器才行。此次项目中要通过模版引擎生成静态页面,然后找到了velocity,能很好的实现这样的功能。
velocity是什么?
官网:http://velocity.apache.org/index.html 点击打开链接
简单解释:Velocity是一个开放源码的模版引擎,Velocity允许我们在模版中设定变量,然后在运行时,动态的将数据插入到模版中,替换这些变量.生成最终表现层页面。
简单的例子:
首先:在eclipse中新建VelocityTest项目
在项目下面新建lib目录存放各种jar包,新建properties目录存放配置文件
然后:需要新建三个文件
a、模版文件
模版文件预设模版,在此新建一个叫hello.vm的模版文件,目录可以随意放,具体目录是通过配置文件来查找的。
<html> <head></head> <body> HELLO! $name,Welcome to velocity! </body> </html>b、配置文件
在properties目录下新建一个Velocity.properties的文件
主要在path那行,是指定你的模版文件所在的目录。否则就会出现找不到目录的提示
#Velocity.properties配置示例 # 如果需要系统从WEB-INF/classes路径加载Velocity的模板文件,取消下面两行的注释 #resource.loader=class #class.resource.loader.class=org.apache.Velocity.runtime.resource.loader.ClasspathResourceLoader #如需禁止系统通过文件系统加载模板文件,注释如下两行 resource.loader=file file.resource.loader.path=G:\Users\xusy\Workspaces\MyEclipse 10\VelocityTest\src #确定从何处加载velocity的模板文件 file.resource.loader.cache=false #设置读取模板文件的解码格式,GB2312是为了支持中文 input.encoding=gb2312 #配置输出视图文件的解码格式,GB2312是为了支持中文 output.encoding=gb2312c、VelocityTest的JAVA代码
在这里需要velocity的一些包的导入,可以到官网上下载
我是在CSDN上下载的 :http://download.csdn.net/detail/zdq56/5120856
其中用到的commons-collections-3.2.1.jar,commons-lang-2.4.jar,commons-logging-1.1.jar,velocity-1.7.jar这4个包,可以放在lib目录下然后引用到项目里面来。
然后编写java代码
import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; public class VelocityTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry { // 初始化 Velocity.init("G:\\Users\\xusy\\Workspaces\\MyEclipse 10\\VelocityTest\\properties\\velocity.properties"); //取得velocity上下文 VelocityContext context = new VelocityContext(); context.put("name", "xusy"); Template template = Velocity.getTemplate("hello.vm"); StringWriter writer = new StringWriter(); template.merge(context, writer); PrintWriter filewriter = new PrintWriter(new FileOutputStream("E:\\a.html"),true); filewriter.println(writer.toString()); filewriter.close(); } catch (Exception e) { e.printStackTrace(); } } }
然后运行之后,就会在E盘目录下发现已经生成a.html,在模版中name已经相应替换成所需要替换的内容了。
- 初识velocity
- 初识Velocity
- 初识Velocity
- Velocity
- Velocity
- Velocity
- Velocity
- Velocity
- Velocity
- velocity
- VELOCITY
- Velocity
- Velocity
- VELOCITY
- velocity
- Velocity
- VELOCITY
- Velocity
- 自定义listview
- sublime 部分插件
- 《从0开始学产品策划》第二期:需求不是终点,而是起点(上)
- 主数据 供应商和客户主数据定义
- zoj1365
- 初识velocity
- SVN服务器搭建和使用(一)
- type 'simple Class' does not conform to protocol 'Example Protocol'错误
- 给VC的控制台程序添加内存泄漏自动检测功能
- [独家干]金错刀:互联网思维是个坑--互联网行动
- as2的LoadVars调外部变量 作用域问题
- 关于上位机与采集器传输文件时有时不响应用户指令问题的解决
- MVC架构在游戏开发中的应用
- SQLite-C编程学习整理