在Java中加载Freemarker模板时出现FileNotFoundException

14

尽管模板实际上存在于路径中,但在加载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)

文件的绝对路径是什么?是哪个操作系统? - Bhavik Shah
请查看我在问题中的更新。 - jaykumarark
5个回答

29

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。(这也意味着模板无法使用../后退,这对于安全性很重要。)

除了从真正的目录加载之外,您还可以从SerlvetContext、"class path"等加载模板。这完全取决于您选择的TemplateLoader

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

更新:如果您收到FileNotFoundException而不是TemplateNotFoundException,那么是时候将FreeMarker升级至至少2.3.22了。它还提供更好的错误消息,例如如果您犯了使用默认TemplateLoader的典型错误,它会在错误消息中直接告诉您。减少开发人员浪费的时间。


我解决了我遇到的问题。当我在eclipse中将应用程序作为一个axis2 webservice运行时,它将eclipse安装文件夹视为模板根目录而不是项目根目录。因此,这就造成了所有的混淆。但你说的很有道理。有没有办法在运行时或项目设置中更改应用程序的根目录? - jaykumarark
正如我所说,您可以通过在Configuration中设置TemplateLoader来设置模板根目录,因为它是TemplateLoader定义模板根目录的部分。 setDirectoryForTemplateLoading仅是一个方便的方法,其通用形式是confg.setTemplateLoader(new WhateverTemplateLoader(...))。您应该在设置Configuration对象的任何地方进行设置。一般情况下,在应用程序生命周期中只需要执行一次,然后所有线程共享相同的Configuration对象。 - ddekany
嘿,谢谢伙计。我尝试了config.setDirectoryForTemplateLoading,当我运行Web服务时它很好用 :) - jaykumarark
1
这个对我很有帮助:https://dev59.com/nXA75IYBdhLWcg3w899J - SparX
谢谢。我因为可以使用vim编辑文件,但是一直收到文件未找到的异常而感到疯狂...这个解决方法对我很有帮助! - Nicholas Terry
显示剩余2条评论

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);


    }   
}

为什么在 FileTemplateLoader templateLoader 中单独给出路径是有效的,但在 configuration.setClassForTemplateLoading 中给出路径却无效? - Akshay Arora

1
实际上,您需要指定模板将放置在哪个目录中的绝对路径(而不是相对路径),请参见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.

例如,这是如何从src/test/resources/freemarker获取模板的方法:
private String final PATH = "src/test/resources/freemarker"
// getting singleton of Configuration
configuration.setDirectoryForTemplateLoading(new File(PATH))
// surrounded by try/catch

0

这个工作像魔法一样顺利,

package tech.service.common;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailingService {


    @Autowired
    private JavaMailSender sender;


    public MailResponseDto sendEmail(String mailTo,String Subject) {
        MailResponseDto response = new MailResponseDto();
        MimeMessage message = sender.createMimeMessage();
        Configuration config = new Configuration(new Version(2, 3, 0));

        try {
            // set mediaType
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            TemplateLoader templateLoader = new FileTemplateLoader(new File("src/main/resources/template"));
            config.setTemplateLoader(templateLoader);
            // add attachment
            helper.addAttachment("logo.png", new File("src/main/resources/static/images/spring.png"));
            Template t = config.getTemplate("email_template_password.ftl");
            Map<String, Object> model = new HashMap<>();
            model.put("Name", "ELAMMARI Soufiane");
            model.put("location", "Casablanca,Morocco");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);

            helper.setTo("example@gmail.com");
            helper.setText(html, true);
            helper.setSubject(Subject);
            sender.send(message);

            response.setMessage("mail send to : " + mailTo);
            response.setStatus(Boolean.TRUE);

        } catch (MessagingException | IOException | TemplateException e) {
            response.setMessage("Mail Sending failure : "+e.getMessage());
            response.setStatus(Boolean.FALSE);
        }

        return response;
    }
}

0
Java虚拟机无法在指定位置找到您的文件/templates/fibplain.xml。这是一个绝对路径,很可能您与相对路径混淆了。要纠正这个问题,请正确使用完整(即绝对)路径,例如/home/jaykumar/templates/fibplan.xml($TEMPLATE_HOME/fibplan.xml)。另一个可能性是,如果您确实有/templates/这样的位置,则可能没有将fibplain.xml放在该位置。对我来说,只有这两个原因最有可能。我假设它是Linux发行版之一,因为分隔符是/

我之前遇到了你提到的问题。我已经解决了它。我在我的问题中详细描述了新的问题,并进行了更新。请评论您的看法。 - jaykumarark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接