问题
Anyone has an example on how to use Freemarker WebappTemplateLoader in FreemarkerConfigurer?
I am using Freemarker with Spring MVC and extending the FreeMarkerConfigurer to add various template loaders and I would also like to add a web app loader to load templates in web app context. But I do not know how to get the servletcontext parameter for its constructor.
public class DesktopFreeMarkerConfigurer extends FreeMarkerConfigurer{
@Override
protected void postProcessConfiguration(Configuration config){
[...]
/* Get templates from the webapp/servlet context */
WebappTemplateLoader watl = new WebappTemplateLoader(<servletContext>, "default/ftl/");
[...]
}
}
I would like to add webapp/default/ftl to template loading path, but as it may be dynamic/configurable, I cannot hardcode it in the xml files.
Any suggestions would be greatly appreciated.
Thank you Carmen
回答1:
I assume you are defining DesktopFreeMarkerConfigurer as a spring bean. In that case, it should be simple to get the servlet context. Just define this in the DesktopFreeMarkerConfigurer class :
@Autowired private ServletContext context;
Or if you choose, you can also make it implements ServletContextAware :
public class DesktopFreeMarkerConfigurer extends FreeMarkerConfigurer implements ServletContextAware {
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
protected void postProcessConfiguration(Configuration config){
WebappTemplateLoader watl = new WebappTemplateLoader(this.servletContext, "default/ftl/");
...
}
...
}
来源:https://stackoverflow.com/questions/14956396/freemarker-webapptemplateloader-in-freemarkerconfigurer