在java中加载freemarker模板时出现FileNotFoundException

时间:2013-02-07 11:05:46

标签: java eclipse freemarker filenotfoundexception

我在加载freemarker模板时遇到文件未找到异常,即使模板实际存在于路径中。

更新:这是作为Web服务运行的。它将根据搜索查询将xml返回给客户端。当我从另一个java程序(来自静态main)调用它时,模板加载成功。但是当客户端请求xml时,会发生FileNotFoundException。

操作系统:Windows 7 文件的绝对路径:C:/ Users / Jay / workspace / WebService / templates /

这是我的代码:

private String templatizeQuestion(QuestionResponse qr) throws Exception
{
    SimpleHash context = new SimpleHash();
    Configuration config = new Configuration();

    StringWriter out = new StringWriter();

    Template _template = null;

    if(condition1)
    {           
        _template = config.getTemplate("/templates/fibplain.xml");
    } 
    else if(condition2)
    {
        _template = config.getTemplate("/templates/mcq.xml");
    }
    context.put("questionResponse", qr);
    _template.process(context, out);

    return out.toString();
 }

完整错误堆栈:

 java.io.FileNotFoundException: Template /templates/fibplain.xml not found.
at freemarker.template.Configuration.getTemplate(Configuration.java:495)
at freemarker.template.Configuration.getTemplate(Configuration.java:458)
at com.hm.newAge.services.Curriculum.templatizeQuestion(Curriculum.java:251)
at com.hm.newAge.services.Curriculum.processQuestion(Curriculum.java:228)
at com.hm.newAge.services.Curriculum.processQuestionList(Curriculum.java:210)
at com.hm.newAge.services.Curriculum.getTest(Curriculum.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:212)
at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:117)
at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

5 个答案:

答案 0 :(得分:25)

FreeMarker模板路径由TemplateLoader对象解析,您应在Configuration对象中指定该对象。您指定为模板路径的路径由TemplateLoader解释,并且通常相对于某种基本目录(即使它以/开头),这也称为模板根目录就是这个原因。在您的示例中,您尚未指定任何TemplateLoader,因此您使用默认的TemplateLoader,这仅用于向后兼容,并且几乎无用(也很危险)。所以,做这样的事情:

config.setDirectoryForTemplateLoading(new File(
    "C:/Users/Jay/workspace/WebService/templates"));

然后:

config.getTemplate("fibplain.xml");

请注意,/template前缀现在不存在,因为模板路径相对于C:/Users/Jay/workspace/WebService/templates。 (这也意味着模板无法用../ - s退出它,这对安全性很重要。)

您也可以从SerlvetContext,"类路径"等加载模板,而不是从真实目录加载。这完全取决于您TemplateLoader的内容选择。

另请参阅:http://freemarker.org/docs/pgui_config_templateloading.html

更新:如果您获得FileNotFoundException而不是TemplateNotFoundException,则需要将FreeMarker升级到至少2.3.22。它还提供了更好的错误消息,例如,如果您执行使用默认TemplateLoader的典型错误,它会在错误消息中告诉您。减少开发人员的浪费时间。

答案 1 :(得分:5)

你可以像这样解决这个问题。

public class HelloWorldFreeMarkerStyle {
    public static void main(String[] args) {

         Configuration configuration = new Configuration();

         configuration.setClassForTemplateLoading(HelloWorldFreeMarkerStyle.class, "/");



        FileTemplateLoader templateLoader = new FileTemplateLoader(new File("resources"));
        configuration.setTemplateLoader(templateLoader);

        Template helloTemp= configuration.getTemplate("hello.ftl");
        StringWriter writer = new StringWriter();
        Map<String,Object> helloMap = new HashMap<String,Object>();
        helloMap.put("name","gokhan");

        helloTemp.process(helloMap,writer);

        System.out.println(writer);


    }   
}

答案 2 :(得分:0)

Java VM无法在指定位置找到您的文件/templates/fibplain.xml。这是an absolute path,您很可能与relative path混淆。要更正这一点,请使用完整(即绝对)路径,如/home/jaykumar/templates/fibplan.xml($TEMPLATE_HOME/fibplan.xml)。其他可能性是,如果你确实有/ templates /这样的位置,你可能没有在该位置放置fibplain.xml。对我来说,只有这两个是最合理的原因。我认为它是linux发行版之一,因为分隔符是/

答案 3 :(得分:0)

这就像吊饰一样,

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.2/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.1/c3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.1/c3.min.css" rel="stylesheet"/>

<div id="chart"></div>

答案 4 :(得分:0)

实际上,您应该为将要放置模板的目录指定绝对路径(不是相对路径),请参见FreeMaker。Configuration

setDirectoryForTemplateLoading(java.io.File dir)
Sets the file system directory from which to load templates.    
Note that FreeMarker can load templates from non-file-system sources too. See setTemplateLoader(TemplateLoader) from more details.

例如,这是从test / resources / freemaker获取模板的方法:

private String final PATH = "src/test/resources/freemaker"
//getting singleton of Configuration
configuration.setDirectoryForTemplateLoading(new File(PATH)) //surrounded by try/catch