需求: 创建Velocity项目,使用Maven2管理项目代码
问题: Velocity模板文件的路径找不到
解决方法:项目的上下文路径为项目名
步骤:
1、创建项目名为webx-app,目录结构为:
webx-app |-- src |-- main |-- java |-- com.mycompany.web.action.SampleServlet
|
|-- resources
|-- webapp |-- web |-- hello.vm
|-- WEB-INF |-- web.xml
|-- index.jsp
|-- target
|-- pom.xml
2、其中,SampleServlet.java代码为:
import java.io.IOException;
import java.io.FileNotFoundException;
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.VelocityContext;
public class SampleServlet extends VelocityServlet {
public Template handleRequest(HttpServletRequest request,HttpServletResponse response, Context ctx) {
Template template = null;
try {
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("name", "Vasilis");
template = Velocity.getTemplate("/web/hello.vm");
} catch (Exception e) {
e.printStackTrace();
} return template;
}
protected Properties loadConfiguration(ServletConfig config) throws IOException,FileNotFoundException {
Properties p = new Properties();
String path = config.getServletContext().getRealPath("/");
if (path == null) {
System.out.println("error");
path = "/";
}
p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
p.setProperty("runtime.log", path + "velocity.log");
return p;
}
}
其中, template = Velocity.getTemplate("/web/hello.vm");里面hello.vm模板路径是相对于上下文webx-app目录。使用Maven2打包后的文件夹结构为:
webx-app |-- META-INF
|-- WEB-INF
| -- web | -- hello.vm