freemarker使用include的异常

首先使用include报错

FreeMarker template error (DEBUG mode; use RETHROW in production!): Template inclusion failed (for parameter value "/views/comm/top.ftl"): Template not found for name "/views/comm/top.ftl". 

模板文件中:

<#include "/views/comm/top.ftl" />

模板路径:

freemarker使用include的异常_第1张图片

模板路径代码中设置template-loader-path为 "/",代表着webapp/路径

 @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer(){
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
        freeMarkerConfigurer.setTemplateLoaderPath("/");
        freeMarkerConfigurer.setDefaultEncoding("UTF-8");
        Properties properties = new Properties();
        properties.put("template_update_delay","10");
        properties.put("defaultEncoding","UTF-8");
        properties.put("url_escaping_charset","UTF-8");
        properties.put("locale","zh_CN");
        properties.put("boolean_format","true,false");
        properties.put("time_format","HH:mm:ss");
        properties.put("datetime_format","yyyy-MM-dd HH:mm:ss");
        properties.put("date_format","yyyy-MM-dd");
        properties.put("number_format","#,###.##");
        properties.put("whitespace_stripping","true");
        properties.put("classic_compatible","true");
        freeMarkerConfigurer.setFreemarkerSettings(properties);
        return freeMarkerConfigurer;
    }

视图解析器中配置的前缀"/WEB-INF/"

 @Bean
    public ViewResolver viewResolver(){
        FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
        viewResolver.setViewClass(FreeMarkerView.class);
        viewResolver.setCache(false);
        viewResolver.setPrefix("/WEB-INF/");
        viewResolver.setSuffix(".ftl");
        viewResolver.setContentType("text/html;charset=utf-8");
        viewResolver.setExposeRequestAttributes(true);
        viewResolver.setExposeSessionAttributes(true);
        viewResolver.setExposeSpringMacroHelpers(true);
        viewResolver.setRequestContextAttribute("rc");
        return viewResolver;
    }

由于template-loader-path属性表示通过TemplateLoader指定从哪个目录开始加载模板,并且把模板加载在缓存中。 

而视图解析器是在Controller的某个方法执行完成以后,返回一个视图,视图解析器要做的工作就是找到某个对象来完成视图的渲染,或者跳转到其他的逻辑视图。

显然<# include>指令加载的模板是走的template-loader-path路径,而不是走视图渲染路径

因此,正确路径应改为:

<#include "/WEB-INF/views/comm/top.ftl" />

freemarker使用include的异常_第2张图片

 

 

 

 

你可能感兴趣的:(freemarker,freemarker)