一、创建spring-freemarker.xml文件,并配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
</beans>
二、编写handler:
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@RequestMapping("/ftl")
@ResponseBody
public String ftl() {
try {
//1、创建configuration对象
Configuration createConfiguration = freeMarkerConfigurer.createConfiguration();
//2、加载模板对象
Template template = createConfiguration.getTemplate("test.ftl");
//3、创建一个数据集
Map map = new HashMap<>();
map.put("hello", "hello spring");
//4、指定文件输出的路径及文件名
Writer out = new FileWriter(new File("C:\\Users\\ZH\\Desktop\\freemarker\\test02"));
//5、输出文件
template.process(map, out);
//6、关闭流
out.close();
return "OK";
} catch (Exception e) {
// TODO: handle exception
}
return "NO";
}