模板引擎(FreeMarkerAPI)

1. 非web方式使用

1.1 maven

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

1.2 常用API

(1) Configuration

方法描述
Configuration(Version version )构造方法,可以设置版本信息
loadBuiltInEncodingMap()
clearEncodingMap()
加载及清除所有编码集
setTemplateLoader(TemplateLoader templateLoader)
getTemplateLoader()
unsetTemplateLoader()
isTemplateLoaderExplicitlySet()
设置及获取模板加载器
清除设置的模板加载器
判断是否设置了模板加载器
setTemplateLookupStrategy(TemplateLookupStrategy templateLookupStrategy)
getTemplateLookupStrategy()
unsetTemplateLookupStrategy()
isTemplateLookupStrategyExplicitlySet()
设置或查看模板查找策略
清除设置的模板查找策略
判断是否设置了模板查找策略
setTemplateNameFormat(TemplateNameFormat templateNameFormat)
getTemplateNameFormat()
unsetTemplateNameFormat()
isTemplateNameFormatExplicitlySet()
设置或查看模板名称格式
清除设置的模板名称格式
判断是否设置了模板名称格式
setTemplateConfigurations(TemplateConfigurationFactory templateConfigurations)
getTemplateConfigurations()
设置或清除模板配置工厂
setCacheStorage(CacheStorage cacheStorage)
getCacheStorage()
unsetCacheStorage()
isCacheStorageExplicitlySet()
设置或查看缓存
清除设置的缓存
判断是否设置了缓存
setDirectoryForTemplateLoading(File dir)加载模板
setServletContextForTemplateLoading(Object servletContext, String path)加载模板
setClassForTemplateLoading(Class resourceLoaderClass, String basePackagePath)加载模板
setClassLoaderForTemplateLoading(ClassLoader classLoader, String basePackagePath)加载模板
setTemplateUpdateDelayMilliseconds(long millis)
getTemplateUpdateDelayMilliseconds()
设置及获取模板更新延迟毫秒
setObjectWrapper(ObjectWrapper objectWrapper)
getObjectWrapper()
unsetObjectWrapper()
isObjectWrapperExplicitlySet()
设置或查看对象包装类
清除设置的对象包装类
判断是否设置了对象包装类
setLocale(Locale locale)
getLocale()
unsetLocale()
isLocaleExplicitlySet()
设置或查看区域对象
清除设置的区域对象
判断是否设置了区域对象
setTimeZone(TimeZone timeZone)
getTimeZone()
unsetTimeZone()
isTimeZoneExplicitlySet()
设置或查看时区
清除设置的时区
判断是否设置了时区
setTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler)
getTemplateExceptionHandler()
unsetTemplateExceptionHandler()
isTemplateExceptionHandlerExplicitlySet()
设置或查看模板异常处理器
清除设置的模板异常处理器
判断是否设置了模板异常处理器
setAttemptExceptionReporter(AttemptExceptionReporter attemptExceptionReporter)
getAttemptExceptionReporter()
unsetAttemptExceptionReporter()
isAttemptExceptionReporterExplicitlySet()
设置或查看异常报告器
清除设置的异常报告器
判断是否设置了异常报告器
setLogTemplateExceptions(boolean value)
getLogTemplateExceptions()
unsetLogTemplateExceptions()
isLogTemplateExceptionsExplicitlySet()
设置或查看是否日志异常
清除设置的是否日志异常
判断是否设置了是否日志异常
setWrapUncheckedExceptions(boolean value)
getWrapUncheckedExceptions()
unsetWrapUncheckedExceptions()
isWrapUncheckedExceptionsExplicitlySet()
设置或查看是否包装未选中异常
清除设置的是否包装未选中异常
判断是否设置了是否包装未选中异常
getStrictSyntaxMode()获取是否严格按语法模式
setIncompatibleImprovements(Version incompatibleImprovements)
getIncompatibleImprovements()
设置或获取版本
setWhitespaceStripping(boolean b)
getWhitespaceStripping()
设置或获取是否空白剥离
setAutoEscapingPolicy(int autoEscapingPolicy)
getAutoEscapingPolicy()
设置或获取自动转移策略
setOutputFormat(OutputFormat outputFormat)
getOutputFormat(String name)
unsetOutputFormat()
isOutputFormatExplicitlySet()
设置或获取输出格式对象
setRegisteredCustomOutputFormats(Collection<OutputFormat> registeredCustomOutputFormats)
getRegisteredCustomOutputFormats()
设置或获取注册的自定义输出格式
setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions)
getRecognizeStandardFileExtensions()
unsetRecognizeStandardFileExtensions()
isRecognizeStandardFileExtensionsExplicitlySet()
设置或获取是否识别标准文件扩展名
清除设置的是否识别标准文件扩展名
判断是否识别标准文件扩展名
setTagSyntax(int tagSyntax)
getTagSyntax()
设置或获取标签语法
setInterpolationSyntax(int interpolationSyntax)
getInterpolationSyntax()
设置或获取插补语法
setNamingConvention(int namingConvention)
getNamingConvention()
设置或获取命名约定
setTabSize(int tabSize)
getTabSize()
设置或获取标签大小
setFallbackOnNullLoopVariable(boolean fallbackOnNullLoopVariable)
getFallbackOnNullLoopVariable()
设置或获取是否循环遍历失败返回null
setPreventStrippings(boolean preventStrippings)
getPreventStrippings()
设置或获取是否防止空白剥离
getTemplate(String name)获取模板对象,可添加其他参数
locale:区域     encoding: 编码    parseAsFTL: 是否解析为ftl
ignoreMissing: 是否忽略缺失    customLookupCondition: 自定义查找条件
setDefaultEncoding(String encoding)
getDefaultEncoding()
unsetDefaultEncoding()
isDefaultEncodingExplicitlySet()
设置或获取默认编码
清除设置的默认编码
判断是默认编码
setEncoding(Locale locale, String encoding)
getEncoding(Locale locale)
设置或获取编码
setSharedVariable(String name, TemplateModel tm)
getSharedVariableNames()
设置或获取共享变量
setAllSharedVariables(TemplateHashModelEx hash)设置所有共享变量
clearTemplateCache()清除模板缓存
removeTemplateFromCache(String name)从缓存中删除模板
setLocalizedLookup(boolean localizedLookup)
getLocalizedLookup()
设置或获取是否本地查找
setSetting(String name, String value)设置配置
getSettingNames(boolean camelCase)获取配置
getVersion()获取版本
getDefaultObjectWrapper(Version incompatibleImprovements)获取默认对象包装
getSupportedBuiltInNames(int namingConvention)获得受支持的内置名称
getSupportedBuiltInDirectiveNames(int namingConvention)获得受支持的内置指令名称

(2) Template

方法描述
Template(String name, Reader reader, Configuration cfg)构造方法,一般通过Configuration对象获取
getPlainTextTemplate(String name, String sourceName, String content, Configuration config)获取纯文本模板
process(Object dataModel, Writer out)处理,通过模板获取文件,dataModel数据Map,还可设置参数
ObjectWrapper 对象包装     TemplateNodeModel  模板节点模型
createProcessingEnvironment(Object dataModel, Writer out)同process方法
getName()获取模板名称
getSourceName()获取原模板名称
getConfiguration()获取配置对象
getParserConfiguration()获取解析配置对象
getTemplateLanguageVersion()获取模板语言版本
getEncoding()获取编码
setCustomLookupCondition(Object customLookupCondition)
getCustomLookupCondition()
设置或获取自定义查找条件
getActualTagSyntax()获取实际标签语法
getInterpolationSyntax()获取插值语法
getActualNamingConvention()获取实际命名约定
setOutputFormat(OutputFormat outputFormat)
getOutputFormat()
设置或输出输出格式
setAutoEscaping(boolean autoEscaping)
getAutoEscaping()
设置或获取自动编码
dump(Writer out)参数可为PrintStream
getSource(int beginColumn, int beginLine, int endColumn, int endLine)获取来源
getDefaultNS()获取默认NS
getNamespaceForPrefix(String prefix)获取前缀的命名空间
getPrefixForNamespace(String nsURI)获取命名空间前缀
getPrefixedName(String localName, String nsURI)获取前缀名称

1.3 自定义函数

1.4 示例

(1) 简单使用

String TEMPLATE_PATH = "D:\\template";//模板路径
String TEMPLATE_NAME = "demo.ftl";//模板名
String CLASS_PATH = "D:\\freemark";//生成文件路径
// step1 创建freeMarker配置实例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
// step2 获取模版路径
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
// step3 创建数据模型
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("demo", "data");
// step4 加载模版文件
Template template = configuration.getTemplate(TEMPLATE_NAME);
// step5 生成数据
File docFile = new File(CLASS_PATH + "\\" + "Demo.txt");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// step6 输出文件
template.process(dataMap, out);
out.flush();

(2) 模板加载方式

 Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
// 方式一 通过文件路径加载
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
// 方式二 从项目根目录中加载
configuration.setClassForTemplateLoading(FreeMarker.class,"/ftl");
// 方式三 web项目从项目根目录中加载
configuration.setClassLoaderForTemplateLoading(FreeMarker.class.getClassLoader(),"/ftl");
// 方式四 web项目从项目根目录中加载
ServletContext context= ContextLoader.getCurrentWebApplicationContext().getServletContext();
configuration.setServletContextForTemplateLoading(context, "/ftl")

2. web方式使用(与springBoot整合)

2.1 maven

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.2 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑重其事,鹏程万里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值