FileNotFoundException when loading freemarker template in java

后端 未结 5 1260
说谎
说谎 2021-01-04 07:40

I get a file not found exception while loading a freemarker template even though the template is actually present in the path.

Update: This is running as a webservi

5条回答
  •  攒了一身酷
    2021-01-04 07:59

    FreeMarker template paths are resolved by a TemplateLoader object, which you should specify in the Configuration object. The path that you specify as the template path is interpreted by the TemplateLoader, and is usually relative to some kind of base directory (even if it starts with /), that's also called the template root directory for this reason. In your example, you haven't specified any TemplateLoader, so you are using the default TemplateLoader, which is only there for backward-compatibility, and is nearly useless (and also dangerous). So, do something like this:

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

    and then:

    config.getTemplate("fibplain.xml");
    

    Note that the /template prefix is not there now, as the template path is relative to C:/Users/Jay/workspace/WebService/templates. (This also means that the template can't back out of it with ../-s, which can be important for security.)

    Instead of loading from a real directory, you can also load templates from a SerlvetContext, from the "class path", etc. It all depends on what TemplateLoader you are choosing.

    See also: http://freemarker.org/docs/pgui_config_templateloading.html

    Update: If you get FileNotFoundException instead of TemplateNotFoundException, it's time to upgrade FreeMarker to at least 2.3.22. It also gives better error messages, like if you do the typical mistake of using the default TemplateLoader, it tells you that right in the error message. Less wasted developer time.

提交回复
热议问题