1.基本实例
导包:
在lib目录内分别copy进:velocity-1.4.jar,velocity-dept.jar;log4j.jar
示例代码:
public class Test
{
public static void main(String[] args)
{
//获取模板引擎
VelocityEngine ve = new VelocityEngine();
//模板文件所在的路径
String path = "D:/work/velocity/WebRoot";
//设置参数
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
//处理中文问题
ve.setProperty(Velocity.INPUT_ENCODING,"GBK");
ve.setProperty(Velocity.OUTPUT_ENCODING,"GBK");
try
{
//初始化模板
ve.init();
//获取模板(hello.html)
Template template = ve.getTemplate("hello.html");
//获取上下文
VelocityContext root = new VelocityContext();
//把数据填入上下文
root.put("name","world");
//输出路径
String outpath = "e:/helloworld.html";
//输出
Writer mywriter = new PrintWriter(new FileOutputStream(
new File(outpath)));
template.merge(root, mywriter);
mywriter.flush();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
2.Servlet和Velocity结合示例
example.html
<table cellspacing="0" cellpadding="5"
width="20%" >
<tr>
<td bgcolor="#eeeeee" align="center">
Names:
</td>
</tr>
#foreach($name in $theList)
<tr>
<td>
$name
</td>
</tr>
#end
</table>
TestVelocityServlet
public class TestVelocityServlet extends VelocityServlet {
/**
* 由TestVelocityServlet.init()调用
* 在此找出模版的路径
*/
protected Properties loadConfiguration(ServletConfig
config)
throws IOException, FileNotFoundException {
//配置模板路径
Properties prop = new Properties();
String path = config.getServletContext().getRealPath("/");
prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
return prop;
}
/**
* Velocity主要的商业逻辑处理方法,由VelocityServlet自动调用
* @param ctx 模板上下文
* @return Template 模板信息
*/
protected Template handleRequest(Context ctx) throws Exception
{
//主要在此设置演示用的数据,开发中在此调用相应的业务处理流程,
//并设置返回到页面的数据
//待展示的列表数据
String p1 = "first";
String p2 = "second";
Vector personList = new Vector();
personList.addElement(new String(p1.getBytes()));
personList.addElement(new String(p2.getBytes()));
//定义模板
Template outty = null;
//设置数据,供页面模版替换成显示的数据
ctx.put("theList", personList);
try {
//取模板
outty = getTemplate("example.html");
} catch (Exception e) {
e.printStackTrace();
}
return outty;
}
}
web.xml
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>com.huang.servlet.TestVelocityServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>
1361

被折叠的 条评论
为什么被折叠?



