2015-09-20 153 views
1

我想用我的Google App Engine Java應用程序部署一些Freemarker模板作爲電子郵件正文模板。我正在使用freemarker-gae-2.3.23.jar。Google App Engine上的ServletContext

我的問題是在戰爭文件中應該放置我的模板文件,以便Freemarker配置類可以找到它們?我以爲WEB-INF/classes/templates會起作用,但我在GAE實例上運行它時遇到以下錯誤。 getRealPath()也不給出任何見解。空字符串被返回。任何想法或建議非常感謝。

SEVERE: Template ./templates/invitation.ftl not found. 
java.lang.RuntimeException: Error in loading ftl template: Template ./templates/invitation.ftl not found. 

我的基本配置如下:

public class FreeMarkerConfig { 

private static FreeMarkerConfig freeMarkerConfig = null; 
private static Configuration cfg = null; 
private static final Logger logger = Logger.getLogger(FreeMarkerConfig.class.getName()); 

private FreeMarkerConfig(ServletContext context){ 
    cfg = new Configuration(); 
    cfg.setServletContextForTemplateLoading(context, "/templates"); 
} 

public static FreeMarkerConfig getInstance(ServletContext context){ 
    if(freeMarkerConfig == null){ 

     freeMarkerConfig = new FreeMarkerConfig(context); 
     return freeMarkerConfig; 
    } 
    return freeMarkerConfig; 
} 

public static Template getTemplateByName(String fileName){ 
    try { 
     return cfg.getTemplate(fileName); 
    } catch(IOException e) { 
     logger.severe(e.getMessage()); 
     e.getStackTrace(); 
     throw new RuntimeException("Error in loading ftl template: "+e.getMessage()); 
    } 
} 
} 

編輯:該解決方案是雙重的。上下文位置是「web」目錄。所以用這個設置freemarker配置解決了這個問題。

private FreeMarkerConfig(ServletContext context){ 
    cfg = new Configuration(); 
    cfg.setServletContextForTemplateLoading(context, "/WEB-INF/classes/templates/"); 
} 

作爲第二個有用的提示,我發現我不得不用模板名稱而不是文件名來請求模板。即邀請而不是邀請.ftl

+0

上述編輯提供的解決方案。 – mba12

+1

你應該添加編輯作爲你的問題的答案。 – Titus

回答

1

該解決方案是兩倍。上下文位置是「web」目錄。所以用這個設置freemarker配置,解決了這個問題。

private FreeMarkerConfig(ServletContext context){ 
    cfg = new Configuration(); 
    cfg.setServletContextForTemplateLoading(context, "/WEB-INF/classes/templates/"); 
    } 

作爲第二個有用的提示,我發現我與模板僅僅是名稱,而不是文件名請求模板。即邀請而不是邀請.ftl