Reputation: 1
Background:
I want to learn the web development by using Velocity and servlet. I use the getServletContext().getRealPath("/")
to find the path of WEB-INF and the .vm file that is stored in /WEB-INF/templates/;
but the path return is :
E:\javaWorkSpcae\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NewVelocity\templates\
what i want is :
E:\javaWorkSpcae\NewVelocity\WebContent\WEB-INF\templates\hello.vm
I use the velocity-tools-1.4, tomcat1.7, jdk1.7
the code i use is:
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;
}
}
who can give me a simple about servlet and velocity, I can not find good example in internet.
Upvotes: 0
Views: 1351
Reputation: 1182
getServletContext().getRealPath("/")
will give you the root of the deployed location of your application which for a tomcat server in eclipse will be the path you are getting because your eclipse tomcat server runs in the directory indicated by that path.
The path "/"
you asked for is the path that you would get if you typed "applicationpath/
" into a browser.
Upvotes: 1