|
@@ -0,0 +1,64 @@
|
|
|
+---
|
|
|
+title: Freemarker
|
|
|
+date: 2018-09-27 11:06:44
|
|
|
+tags: freemarker
|
|
|
+categories: java
|
|
|
+---
|
|
|
+### Freemarker 杂记
|
|
|
+
|
|
|
+__需求:__ 使用freemarker渲染生成模板文件
|
|
|
+
|
|
|
+freemarker常用与web项目前端页面渲染,同样也可以用于其他代码的模板化生成
|
|
|
+#### 方法1
|
|
|
+使用自带的Configuration
|
|
|
+```
|
|
|
+import freemarker.template.Configuration;
|
|
|
+
|
|
|
+Configuration cfg = new
|
|
|
+//指定Freemarker版本
|
|
|
+Configuration(Configuration.VERSION_2_3_28);
|
|
|
+//模板文件夹存放地址
|
|
|
+File file = new File("");
|
|
|
+cfg.setDirectoryForTemplateLoading(file);
|
|
|
+//设置封装格式
|
|
|
+vfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_28));
|
|
|
+
|
|
|
+//获取文件
|
|
|
+//文件路径加文件名
|
|
|
+Template template = cfg.getTemplate("fileName","UTF-8");
|
|
|
+//param 为输出参数
|
|
|
+Writer out = new StringWriter();
|
|
|
+template.process(params, out);
|
|
|
+out.toString();
|
|
|
+```
|
|
|
+#### 方法2
|
|
|
+如果freemarker已经与spring集成可以直接通过配置文件指定多个模板文件地址(推荐)
|
|
|
+- springboot 配置
|
|
|
+```
|
|
|
+spring.freemarker.template-loader-path=classpath:/templates/page,classpath:/code_temp
|
|
|
+```
|
|
|
+
|
|
|
+- springMvc 配置(未测试)
|
|
|
+```
|
|
|
+<bean id="freemarkerConfig"
|
|
|
+ class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
|
|
|
+ <property name="templateLoaderPaths" >
|
|
|
+ <list>
|
|
|
+ <value>"/WEB-INF/page"</value>
|
|
|
+ <value>"/code_temp"</value>
|
|
|
+ </list>
|
|
|
+ </property>
|
|
|
+</bean>
|
|
|
+```
|
|
|
+代码逻辑与方法1类似
|
|
|
+```
|
|
|
+@Autowired
|
|
|
+private freemarker.template.Configuration configuration;
|
|
|
+
|
|
|
+//templateFile 文件路径及文件
|
|
|
+Template template = configuration.getTemplate(templateFile, "UTF-8");
|
|
|
+Writer out = new StringWriter();
|
|
|
+//param 为输出参数
|
|
|
+template.process(params, out);
|
|
|
+out.toString();
|
|
|
+```
|