How can I configure freemarker to search templates in several jars? With spring.
<!-- freemarker config -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="classpath:/freemarker/" />
</bean>
One war file (to deploy), and jar file (in dependencies).
One.war
/freemarker/simple.ftl
Two.jar
/freemarker/test.ftl
Work.
ModelAndView mav = new ModelAndView();
mav.setViewName("simple");
Do not work. Can't find test.ftl
ModelAndView mav = new ModelAndView();
mav.setViewName("test");
If settings is:
<property name="templateLoaderPaths" value="classpath:/freemarker/,classpath:/freemarker2/" />
One.war
/freemarker/simple.ftl
Two.jar
/freemarker2/test.ftl
Work.
ModelAndView mav = new ModelAndView();
mav.setViewName("simple");
Work.
ModelAndView mav = new ModelAndView();
mav.setViewName("test");
And question! How configure freemarker to search in several jars(wars) in same path (classpath:/freemarker/)?
I found solution! Turn off preferFileSystemAccess to always load via SpringTemplateLoader.
<!-- freemarker config -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="classpath:/freemarker/" />
<property name="preferFileSystemAccess" value="false" />
</bean>
public void setPreferFileSystemAccess(boolean preferFileSystemAccess)
Set whether to prefer file system access for template loading. File system access enables hot detection of template changes.
If this is enabled, FreeMarkerConfigurationFactory will try to resolve the specified "templateLoaderPath" as file system resource (which will work for expanded class path resources and ServletContext resources too).
Default is "true". Turn this off to always load via SpringTemplateLoader (i.e. as stream, without hot detection of template changes), which might be necessary if some of your templates reside in an expanded classes directory while others reside in jar files.
Once I did a similar thing programmatically :
public class ControllerServlet extends HttpServlet {
private Configuration cfg;
public void init() {
cfg = new Configuration();
// 1
WebappTemplateLoader wtl = new WebappTemplateLoader(getServletContext(), "WEB-INF/templates");
// 2
ClassTemplateLoader ctl = new ClassTemplateLoader(ControllerServlet.class, "templates");
MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] {wtl, ctl});
cfg.setTemplateLoader(mtl);
//....
}
}
ControllerServlet is a base class for my real servlets.
Number 1 sets the search path for templates to {{WEB-INF/templates}} in the current servlet context. Number 2 sets a second search path to the subpackage "templates".
You may add more template paths.
Hope it helps.
来源:https://stackoverflow.com/questions/6870750/freemarker-templates-in-several-jars