在基于WEB的应用中,通常大多数情况下是在servlet里使用Velocity。在servlet里的Velocity基本应用是非常简单的,只需通过两个必要步骤就可以实现:
1. 继承org.apache.velocity.servlet.VelocityServlet抽象类:
public class SampleServlet extends VelocityServlet
2. 仅需实现VelocityServlet类的一个方法handleRequest():
public Template handleRequest(HttpServletRequest req, HttpServletResponse resp, Context context)
创建一个web工程,在webroot下建立templates文件夹以存放模板文件。
在src下建立velocity.properties配置文件,内容如下:
file.resource.loader.path = templates ##指定模板文件存放目录
runtime.log = log/velocity.log ##指定日志文件位置
关于Velocty中出现中文乱码问题,可以在velocity.properties文件中加入下面的三行就可以解决:
default.contentType=text/html; charset=UTF-8
input.encoding=UTF-8
output.encoding=UTF-8
在templates文件夹中建立名为sample.vm的模板,内容如下:
接着我们需要开发自己的Servlet,这个Servlet继承VelocityServlet。
然后在web.xml中配置这个Servlet,如下:
部署并启动工程,之后执行这个Servlet,浏览器便会显示使用vm模板展示的页面。
org.apache.velocity.servlet.VelocityServlet继承了HttpServlet,因此它继承了HttpSetvlet的对生命周期的管理,而且,只要我们在实现自己velocity servlet的时候,继承org.apache.velocity.servlet.VelocityServlet,然后继承它的一些重要的方法就可以完成实际的业务。
当web工程启动时,系统会先执行SampleServlet的父类VelocityServlet中的init()方法。
VelocityServlet源代码:
在执行VelocityServlet类的initVelocity方法时,因为SampleServlet类继承并重写了其中所调用的loadConfiguration方法,故系统会执行SampleServlet类的loadConfiguration方法。该过程获取了自行设置velocity日志文件的位置和自行设置模板的位置。
在这个过程中,Velocity会自行访问velocity.properties配置文件,以读取其中的信息。如果不配置该配置文件,或者不配置key为file.resource.loader.path的项,在执行Template outty = getTemplate("sample.vm");语句或Template outty = getTemplate("/templates/sample.vm");时,会发生无法找到模板的错误。
至此,Velocity在容器启动初始化完毕。
当在浏览器中输入http://localhost:8080/Mixele_Velocity/SampleServlet时,Velocity的处理过程为:
从执行SampleServlet父类VelocityServlet的doGet开始 --> doRequest --> createContext --> setContentType --> chooseCharacterEncoding --> handleRequest(SampleServlet继承) --> getTemplate(String name) --> mergeTemplate(将模板和嵌入模板中的值合并) --> requestCleanup
1. 继承org.apache.velocity.servlet.VelocityServlet抽象类:
public class SampleServlet extends VelocityServlet
2. 仅需实现VelocityServlet类的一个方法handleRequest():
public Template handleRequest(HttpServletRequest req, HttpServletResponse resp, Context context)
创建一个web工程,在webroot下建立templates文件夹以存放模板文件。
在src下建立velocity.properties配置文件,内容如下:
file.resource.loader.path = templates ##指定模板文件存放目录
runtime.log = log/velocity.log ##指定日志文件位置
关于Velocty中出现中文乱码问题,可以在velocity.properties文件中加入下面的三行就可以解决:
default.contentType=text/html; charset=UTF-8
input.encoding=UTF-8
output.encoding=UTF-8
在templates文件夹中建立名为sample.vm的模板,内容如下:
<html>
<head><title>Sample velocity page</title></head>
<body bgcolor="#ffffff">
<center>
<h2>Hello Velocity</h2>
<table width="100" cellpadding="5" cellspacing="1" bordercolor="#333333">
<tr><td bgcolor="#eeeeee" align="center">Names</td></tr>
#foreach ($name in $theList)
<tr><td bgcolor="#6666FF" align="center">$name</td></tr>
#end
</table>
</center>
</body>
</html>
接着我们需要开发自己的Servlet,这个Servlet继承VelocityServlet。
public class SampleServlet extends VelocityServlet {
private static final long serialVersionUID = 1L;
/** for setting up the Velocity runtime 在系统启动时执行该方法
* Loads the configuration information and returns that information as a Properties,
* which will be used to initialize the Velocity runtime. */
protected Properties loadConfiguration(ServletConfig config)
throws IOException, FileNotFoundException {
String propsFile = config.getInitParameter(INIT_PROPS_KEY); //读取配置文件
Properties p = new Properties();
if (propsFile != null) {
String realPath = getServletContext().getRealPath(propsFile);
if (realPath != null) {
propsFile = realPath;
}
p.load(new FileInputStream(propsFile));
}
String log = p.getProperty(Velocity.RUNTIME_LOG); //设置velocity日志文件的位置
if (log != null) {
log = getServletContext().getRealPath(log);
if (log != null) { p.setProperty(Velocity.RUNTIME_LOG, log); }
}
String path = p.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH); //设置模板的位置
if (path != null) {
path = getServletContext().getRealPath(path);
if (path != null) { p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); }
}
return p;
}
/** Implement this method to add your application data to the context,
* calling the getTemplate() method to produce your return value. */
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
String p1 = "Hoffman";
String p2 = "Song";
Vector personList = new Vector();
personList.addElement(p1);
personList.addElement(p2);
ctx.put("theList", personList); //将模板数据 list放置到上下文环境context中
Template outty = null;
try {
outty = getTemplate("sample.vm");
} catch (ParseErrorException pee) {
System.out.println("SampleServlet : parse error for template " + pee);
} catch (ResourceNotFoundException rnfe) {
System.out.println("SampleServlet : template not found " + rnfe);
} catch (Exception e) {
System.out.println("Error " + e);
}
return outty;
}
}
然后在web.xml中配置这个Servlet,如下:
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>com.mixele.velocity.SampleServlet</servlet-class>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/classes/velocity.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/SampleServlet</url-pattern>
</servlet-mapping>
部署并启动工程,之后执行这个Servlet,浏览器便会显示使用vm模板展示的页面。
org.apache.velocity.servlet.VelocityServlet继承了HttpServlet,因此它继承了HttpSetvlet的对生命周期的管理,而且,只要我们在实现自己velocity servlet的时候,继承org.apache.velocity.servlet.VelocityServlet,然后继承它的一些重要的方法就可以完成实际的业务。
当web工程启动时,系统会先执行SampleServlet的父类VelocityServlet中的init()方法。
VelocityServlet源代码:
/** 初始化Veocity */
public void init(ServletConfig config) throws ServletException {
super.init(config);
initVelocity(config); //初始化Velocity
/* Velocity初始化时修改部分配置 */
defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
System.out.println("defaultContentType = "+defaultContentType);
}
/** Velocity在运行时初始化,读取Velocity配置文件 */
protected void initVelocity(ServletConfig config) throws ServletException {
try {
Properties props = loadConfiguration(config); //读取velocity.properties
Velocity.init(props); //初始化Velocity
} catch (Exception e) {
throw new ServletException("Error initializing Velocity: " + e, e);
}
}
在执行VelocityServlet类的initVelocity方法时,因为SampleServlet类继承并重写了其中所调用的loadConfiguration方法,故系统会执行SampleServlet类的loadConfiguration方法。该过程获取了自行设置velocity日志文件的位置和自行设置模板的位置。
在这个过程中,Velocity会自行访问velocity.properties配置文件,以读取其中的信息。如果不配置该配置文件,或者不配置key为file.resource.loader.path的项,在执行Template outty = getTemplate("sample.vm");语句或Template outty = getTemplate("/templates/sample.vm");时,会发生无法找到模板的错误。
至此,Velocity在容器启动初始化完毕。
当在浏览器中输入http://localhost:8080/Mixele_Velocity/SampleServlet时,Velocity的处理过程为:
从执行SampleServlet父类VelocityServlet的doGet开始 --> doRequest --> createContext --> setContentType --> chooseCharacterEncoding --> handleRequest(SampleServlet继承) --> getTemplate(String name) --> mergeTemplate(将模板和嵌入模板中的值合并) --> requestCleanup