freemarker模板加載TemplateLoader常見方式


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

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

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

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

ClassTemplateLoader, FileTemplateLoader, MultiTemplateLoader, StringTemplateLoader, URLTemplateLoader, WebappTemplateLoader  

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

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

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

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

Configuration cfg = new Configuration();  
              
            TemplateLoader templateLoader=null;  
            String path="";  
              
            templateLoader=new ClassTemplateLoader(PageTag.class,"templates/page/");  
            path="standardd.ftl";  
              
            cfg.setTemplateLoader(templateLoader);  
            Template t=cfg.getTemplate(path,"UTF-8");  

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

其它的加載器原理同上。

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

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

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


免責聲明!

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



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