1.需要大概涉及到的jar文件
2.配置Servlet请求地址
<servlet>
<servlet-name>velc</servlet-name>
<servlet-class>cn.lcr.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>velc</servlet-name>
<url-pattern>/dotest</url-pattern>
</servlet-mapping> </servlet>
3.通过Servlet请求并加载数据信息
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
VelocityContext ctx=new VelocityContext();
Person per=new Person();
per.setAge(18);
per.setName("Joe");
per.setSex("female");
request.setAttribute("per",per);
String[] arrs=new String[]{"one","two","three"};
ctx.put("hl", "hello world");
ctx.put("ho", "hello guy");
request.setAttribute("ctx","ctxAAAA");
request.setAttribute("arrs",arrs);
Map<String, Object> map=new HashMap<String, Object>();
map.put("map1","mapx");
request.setAttribute("map",map);
request.getSession().setAttribute("ctx1","重定向ctxccc");
ctx.put("per",per);
ctx.put("arrs",arrs);
ctx.put("map",map);
ctx.put("ctx","hello this is a control");
//转发请求
//request.getRequestDispatcher("indexv.html").forward(request, response);
//重定向请求
//response.sendRedirect("indexv.vm");
//Velocity模板引擎跳转
try {
VelocityParser.render("indexv.html", ctx, request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
然后将数据信息载入并跳转打印模板文件
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
#set($hello="velocity hello")
this is the word : $hello
hi $!ctx d
$!ctx1
<div>----------数组-----</div>
#foreach($arr in $arrs)
<div>$arr</div>
#end
<div>----------object-----</div>
$!per.name
$!per.age
$!per.sex
<br/>
-----map--------<br/>
$map.map1
<div>----------宏定义-----</div>
#macro(tablerows $arrsList)
<table style="color: red;">
#foreach($arr in $arrsList)
<tr>
<td bgcolor="red">$arr</td>
<td bgcolor="blue">P</td>
<td bgcolor="yellow">F</td>
</tr>
#end
</table>
#end
#macro ( A )
<DIV>m...
<TABLE>..
#end
#tablerows($arrs)
<div>----------宏定义2-----</div>
#macro(d)
<table style="border: 1px solid;">
#foreach($arr in $arrs)
<tr>
<td><div>$arr</div></td>
</tr>
#end
</table>
#end
#d()
<div>..........................</div>
<table style="color: red;">
#foreach($arr in $arrs)
<tr>
<td bgcolor="red">$arr</td>
<td bgcolor="blue">P</td>
<td bgcolor="green">S</td>
</tr>
#end
</table>
<div>..........................</div>
#parse("inc/head.html")
#parse("inc/body.html")
#include("inc/head.html","inc/body.html")
</body>
</html>