创建Velocity项目,使用Maven2管理

需求: 创建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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值