Velocity可以方便的对页面进行管理,先看两个实例:
在java applicate里面:
1.导入相应的jar包
2.建立*.vm文件
3.在主方法里面编写.对*.vm里面的文件赋值语句
<!--StartFragment -->
在java web里面:
1.建立一个vm模板
2.建立一个servlet继承VelocityServlet
3.重写里面的方法
这个方法就是初始化得到一些properties属性,相当于servlet的init()方法
protected Properties loadConfiguration(ServletConfig config)
throws IOException, FileNotFoundException {
System.out.println("初始化...");
Properties p = new Properties();
String path = config.getServletContext().getRealPath("/");
if (path == null) {
System.out.println(" SampleServlet.loadConfiguration() : unable to "
+ "get the current webapp root. Using '/'. Please fix.");
path = "/";
}
p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
p.setProperty("runtime.log", path + "velocity.log");
return p;
}
throws IOException, FileNotFoundException {
System.out.println("初始化...");
Properties p = new Properties();
String path = config.getServletContext().getRealPath("/");
if (path == null) {
System.out.println(" SampleServlet.loadConfiguration() : unable to "
+ "get the current webapp root. Using '/'. Please fix.");
path = "/";
}
p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
p.setProperty("runtime.log", path + "velocity.log");
return p;
}
这个方法是给模板赋值的方法,相当于servlet的里面的dopost或者doget
public Template handleRequest(HttpServletRequest request,HttpServletResponse response, Context ctx) {
System.out.println("ok");
Template template = null;
try {
/**
* 主要代码
*/
Velocity.init();
/**
* 注意相对路径
*/
List list=new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
template = Velocity.getTemplate("/hello.vm");//得到模板的信息
ctx.put("list", list);//把模板里面的变量进行赋值,模板里面有一个$list
} catch (Exception e) {
e.printStackTrace();
}
return template;//返回一个修改后的模板
}
System.out.println("ok");
Template template = null;
try {
/**
* 主要代码
*/
Velocity.init();
/**
* 注意相对路径
*/
List list=new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
template = Velocity.getTemplate("/hello.vm");//得到模板的信息
ctx.put("list", list);//把模板里面的变量进行赋值,模板里面有一个$list
} catch (Exception e) {
e.printStackTrace();
}
return template;//返回一个修改后的模板
}