spring boot加载freemarker模板路径的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring boot加载freemarker模板路径的方法

xiaotao_i   2020-11-27 我要评论

1,之前用的eclipse开发工具来加载spring boot加载freemarker模板路径,现在换用idea却不能使用了,所以来记录一下
加载freemarker模板三种方式,如下

public void setClassForTemplateLoading(Class clazz, String pathPrefix);

public void setDirectoryForTemplateLoading(File dir) throws IOException;

public void setServletContextForTemplateLoading(Object servletContext, String path);

看名字也就知道了,分别基于类路径、文件系统以及Servlet Context。
第一种是我用idea,spring boot加载freemarker配置的
①首先设置spring boot加载freemarker模板的配置(代替了xml配置),如下

在这里插入图片描述

②通过Configuration来获取freemarker文件路径

在这里插入图片描述

这个方法是根据类加载路径来判断的,最终会执行以下代码

FreemarkerUtil.class.getClassLoader().getResource("/template/");

第二种基于文件系统。 比如加载/home/user/template下的模板文件。

Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("/home/user/template"));
cfg.getTemplate("Base.ftl");

这样就获得了/home/user/template/Base.ftl这个模板文件
第三种基于web project。 第二个参数是基于WebRoot下的。
使用xml配置来看看

在这里插入图片描述
在这里插入图片描述

这里注意一下第二个参数需要以 “/” 开头。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们