在使用velocity過程中,總是出現.ResourceNotFoundException異常,找不到模板.vm文件。現公布解決辦法:
研究velocity源碼:
關鍵是
ClassLoader classLoader = super.getClass().getClassLoader();
result = classLoader.getResourceAsStream(name);
這兩行代碼。是在你的Classpath下去load, 所以必須保證vm文件存在于WEB-INF/classes 下
import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import java.io.StringWriter; import java.util.Properties; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; public class VelocityTest { public static void main(String[] args) { try { /* first, get and initialize an engine */ VelocityEngine ve = new VelocityEngine(); Properties properties = new Properties(); String basePath = "src/com/worthtech/app/test";//這里需要這樣寫路徑!!! // 設置模板的路徑 properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath); // 初始花velocity 讓設置的路徑生效 ve.init(properties); /* next, get the Template */ Template t = ve.getTemplate("vm.vm"); /* create a context and add data */ VelocityContext context = new VelocityContext(); context.put("name", "DingDangXiaoMa"); context.put("site", "http://www.sun.com"); /* now render the template into a StringWriter */ StringWriter writer = new StringWriter(); t.merge(context, writer); /* show the World */ System.out.println(writer.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

研究velocity源碼:
public synchronized InputStream getResourceStream(String name) throws ResourceNotFoundException { InputStream result = null; if ((name == null) || (name.length() == 0)) { throw new ResourceNotFoundException("No template name provided"); } try { ClassLoader classLoader = super.getClass().getClassLoader(); result = classLoader.getResourceAsStream(name); } catch (Exception fnfe) { throw new ResourceNotFoundException(fnfe.getMessage()); } return result; }
關鍵是
ClassLoader classLoader = super.getClass().getClassLoader();
result = classLoader.getResourceAsStream(name);
這兩行代碼。是在你的Classpath下去load, 所以必須保證vm文件存在于WEB-INF/classes 下
velocity使用中出現org.apache.velocity.exception.ResourceNotFoundException的解決辦法
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
