freemarker報 java.io.FileNotFoundException:及TemplateLoader使用


  使用過freemarker的肯定其見過如下情況: 

1 java.io.FileNotFoundException: Template xxx.ftl not found.  



模板找不到。可能你會認為我明明指定了文件,並且文件存在,但是為什么就是說找不到呢? 
經過研究官方的API,原來freemarker在加載模板時,建議使用TemplateLoader,通過TemplateLoader指定從哪個目錄開始加載模板,並且把模板加載在緩存中。 

   API的TemplateLoader是一個接口,他有如下幾個實現類: 

1 ClassTemplateLoader, FileTemplateLoader, MultiTemplateLoader, StringTemplateLoader, URLTemplateLoader, WebappTemplateLoader 


   顧名思義,我們能從類名中猜想到freemarker的模板加載機制,舉例說明兩個: 

1:FileTemplateLoader 
  此是文件模板加載器,此即可以通過文件的絕對路徑加載模板,如: 

1 TemplateLoader templateLoader=null;  
2            String path="";  
3              
4            //使用FileTemplateLoader  
5           templateLoader=new FileTemplateLoader(new File("項目根路徑"));  
6           path="/WEB-INF/classes/com/xxx/tag/templates/page/xxx.ftl";  
7                          
8            cfg.setTemplateLoader(templateLoader);  
9            Template t=cfg.getTemplate(path,"UTF-8");

 

 

2:ClassTemplateLoader 
  此是通過指定類所在的目錄來指定模板所在根路徑,即指定類在哪個目錄,那么這個目錄就是加載模板文件的根目錄,如下: 

 1 Configuration cfg = new Configuration();  
 2               
 3             TemplateLoader templateLoader=null;  
 4             String path="";  
 5               
 6             templateLoader=new ClassTemplateLoader(PageTag.class,"templates/page/");  
 7             path="standardd.ftl";  
 8               
 9             cfg.setTemplateLoader(templateLoader);  
10             Template t=cfg.getTemplate(path,"UTF-8"); 


此即表示比PageTag類所在的目錄開始找,找這個目錄下的templates/page/目錄, 

其它的加載器原理同上, 

如果你是web項目,並且使用了spring,那么。你還可以通過spring來配置你模板文件的根目錄,如下: 

1 <bean id="freemarkerConfig" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">  
2     <property name="templateLoaderPath" value="/WEB-INF" />  
3      <property name="freemarkerSettings">  
4         <props>         
5             <prop key="defaultEncoding">UTF-8</prop>         
6         </props>         
7     </property>  
8 </bean> 

 

此即表示從WEB-INF目錄下開始找。 

 

 

 

 

 

 

原文:http://zwllxs.iteye.com/blog/996244


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM