鍩虹鎼緩錛氫粠緗戜笂涓嬭澆velocity.zip錛屾妸lib涓嬬殑.jar鏂囦歡瀵煎叆鍒板伐紼嬩腑銆傚彟澶栬繕瑕佸鍏elocity.jar 鍜寁elocity-dep.jar.
hellosite.vm 鏀懼埌宸ョ▼鐨勭洰褰曞簳涓嬨?br />
Hello $name! Welcome to $site world!
HelloWorld.java
package com;
import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class HelloWorld {
public static void main(String[] args) throws Exception {
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();
/* next, get the Template */
Template t = ve.getTemplate("hellosite.vm");
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "DingDangXiaoMa");
context.put("site", "http://www.sun.com");
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge(context, writer);
/* show the World */
System.out.println(writer.toString());
}
}
鐩存帴榪愯榪欎釜紼嬪簭錛屽氨鍙互杈撳叆妯℃澘涓殑淇℃伅銆?br />
2銆倃eb紼嬪簭錛宻ervlet 璋冪敤vm鏄劇ず淇℃伅銆?br />
hello.vm 鏀懼湪webRoot/web/涓嬨?br />
<html>
<body >
#set($name="Hello ! DingDang")
Hello, $name
woowoo
</body>
</html>
servlet 鏂囦歡錛?br />
public class SampleServlet extends VelocityServlet {
protected Properties loadConfiguration(ServletConfig config)
throws IOException, FileNotFoundException {
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;
}
public Template handleRequest(HttpServletRequest request,
HttpServletResponse response, Context ctx) {
/**
* 鎴戠殑涓浜涙祴璇曡緭鍑?br />
*/
System.out.println("Hello everyone");
System.out.println("sfdsfsd");
System.out.println(ctx);
System.out.println(ctx.toString());
System.out.println(request.getContextPath());
Template template = null;
try {
/**
* 涓昏浠g爜
*/
Velocity.init();
/**
* 娉ㄦ剰鐩稿璺緞
*/
template = Velocity.getTemplate("/web/hello.vm");
VelocityContext context = new VelocityContext();
context.put("name", "wowowowowowo hello hello hello");
// template = Velocity.getTemplate("/web/sample.html");
} catch (Exception e) {
e.printStackTrace();
}
return template;
}
}
浠ヤ笂灝辨槸涓や釜鏈綆鍗曠殑velocity鐨勪緥瀛愩?涓涓槸java application 涓涓槸java web紼嬪簭銆?br />
鍙傝冭祫鏂欙細
http://www.javaresearch.org/article/38895.htm

]]>