(1)Maven的pom.xml里加
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
(2)spring配置文件里加:
<bean id="freeMarkerConfigurationFactory" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"> <property name="templateLoaderPath" value="/WEB-INF/freemarker/" /> <property name="preferFileSystemAccess" value="false" /> </bean>
<bean id="freeMarkerConfiguration" class="freemarker.template.Configuration" factory-bean="freeMarkerConfigurationFactory" factory-method="createConfiguration" scope="prototype" />
(3)代码里
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import freemarker.template.Configuration; import freemarker.template.Template;
@Autowired private Configuration freemarkerConfiguration;
Map<String, Object> map = new HashMap<String, Object>(); map.put("aaa", 1);
Template tpl = freemarkerConfiguration.getTemplate("daily.ftl"); String content = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
------------------------------------ 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.
好像是模板文件在jar包里什么的,得设置成false。 默认是true,认为是文件,可以监控到模板文件的变更~
|