我的开发环境是Eclipse3.0.8
一、 先建一个WEB工程,如下图:
二、 建一个hello.vm文件,存放目录如上图
文件内容如下:
<html>
<body >
#set($name="wang mo ref ")
Hello, $name
woowoo
</body>
</html>
三、 创建SampleServlet.java对象,目录结构如上图
内容如下:
package zy.pro.nm.nt;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.StringWriter;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
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) {
/**
*我的一些测试输出
**/
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 {
/**
*主要代码
**/
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("name", "wowowowowowo hello hello hello");
//template = Velocity.getTemplate("/web/sample.html");
/**
*注意相对路径,请参考如上图目录
**/
template = Velocity.getTemplate("/web/hello.vm");
} catch (Exception e) {
e.printStackTrace();
}
/*
try{
VelocityEngine ve = new VelocityEngine();
ve.init();
template = ve.getTemplate("/web/hello.vm");
VelocityContext context = new VelocityContext();
context.put("name", "Eiffel Qiu");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}catch(Exception e){
e.printStackTrace();
}
*/
return template;
}
}
四、 在Tomcat 中发布,运行结果如下:
velocity例子
最新推荐文章于 2024-06-15 16:41:34 发布