14

テンプレートが実際にパスに存在していても、フリーマーカーテンプレートの読み込み中にファイルが見つからないという例外が発生します。

更新:これはWebサービスとして実行されています。検索クエリに基づいてクライアントにxmlを返します。テンプレートを別のJavaプログラム(静的メインから)から呼び出すと、テンプレートは正常にロードされます。ただし、クライアントがxmlを要求すると、FileNotFoundExceptionが発生します。

OS:Windows 7ファイルの絶対パス:C:/ Users / Jay / worksheet / 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通常、ある種のベースディレクトリ(で始まる場合でも/)に相対的です。このため、これはテンプレートルートディレクトリとも呼ばれます。あなたの例では、何も指定していない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表示され、エラーメッセージにその旨が表示されます。開発者の無駄な時間を減らします。

于 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

実際には、テンプレートが配置されるdirの絶対パス(相対パスではない)を指定する必要があります。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

/templates/fibplain.xmlJava VMは、指定された場所にあるファイルを見つけることができません。これはan absolute path 、と混同されている可能性が高いですrelative path。これを修正するには、のように完全な(つまり絶対的な)パスを適切に使用します/home/jaykumar/templates/fibplan.xml($TEMPLATE_HOME/fibplan.xml)。他の可能性としては、/ templates /などの場所がある場合、その場所にfibplain.xmlを配置していない可能性があります。私にとって、これら2つだけが最ももっともらしい理由です。セパレータが/

于 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 に答える