14

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

更新:这是作为网络服务运行的。它将根据搜索查询向客户端返回一个 xml。当我从另一个 java 程序(从静态主程序)调用模板时,模板加载成功。但是当客户端请求 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)
4

5 回答 5

29

FreeMarker 模板路径由一个TemplateLoader对象解析,您应该在对象中指定该Configuration对象。您指定为模板路径的路径由 解释TemplateLoader,并且通常相对于某种基目录(即使它以 开头/),因此也称为模板根目录。在您的示例中,您没有指定 any TemplateLoader,因此您使用的是 default 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,它会在错误消息中告诉您正确的信息。减少浪费的开发人员时间。

于 2013-02-07T21:53:49.440 回答
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);


    }   
}
于 2015-06-26T14:33:41.853 回答
1

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

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
于 2019-09-09T11:18:09.660 回答
0

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

于 2013-02-07T11:16:10.873 回答
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;
    }
}
于 2019-06-15T21:34:27.617 回答