背景:
我想通过使用Velocity和servlet来学习Web开发。我使用getServletContext().getRealPath("/")
来查找WEB-INF的路径和存储在/ WEB-INF / templates /中的.vm文件;
但路径返回是:
E:\javaWorkSpcae\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NewVelocity\templates\
我想要的是:
E:\javaWorkSpcae\NewVelocity\WebContent\WEB-INF\templates\hello.vm
我使用velocity-tools-1.4, tomcat1.7, jdk1.7
我使用的代码是:
package velocityHandler;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.servlet.VelocityViewServlet;
public class HelloHandler extends VelocityViewServlet{
private static final long serialVersionUID = 1L;
private VelocityEngine velo;
@Override
public void init() throws ServletException{
//velocity引擎对象
velo = new VelocityEngine();
//设置vm模板的装载路径
Properties prop = new Properties();
String path = this.getServletContext().getRealPath("/");
prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path + "templates");
System.out.println(path + "templates/");
try {
//初始化设置,下面用到getTemplate("*.vm")输出时
//一定要调用velo对象去做,即velo.getTemplate("*.vm")
velo.init(prop);
} catch (Exception e1) {
e1.printStackTrace();
}
}
@SuppressWarnings("unchecked")
@Override
protected Template handleRequest(HttpServletRequest request,
HttpServletResponse response, Context ctx) throws Exception{
String p1 = "Hoffman";
String p2 = "Song";
@SuppressWarnings("rawtypes")
Vector personList = new Vector();
personList.addElement(p1);
personList.addElement(p2);
ctx.put("theList", personList); //将模板数据 list放置到上下文环境context中
Template template = velo.getTemplate("hello.vm");
return template;
}
}
谁能给我一个关于servlet和速度的简单,我在网上找不到好的例子。
答案 0 :(得分:1)
getServletContext().getRealPath("/")
将为您提供应用程序部署位置的根目录,因为您的eclipse tomcat服务器在该路径指示的目录中运行,因此eclipse中的tomcat服务器将成为您获取的路径。
您要求的路径"/"
是您键入" applicationpath/
"的路径。进入浏览器。