Freemarker WebappTemplateLoader in FreemarkerConfigurer

我怕爱的太早我们不能终老 提交于 2019-12-12 05:18:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!