添加jar包
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
配置文件
freeMarkerConfigurer
<!-- freemarker的配置 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
加载配置文件
Web.xml加载springmvc.xml
<!-- 前端控制器 -->
<servlet>
<servlet-name>taotao-item-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Controller
业务逻辑:
1、从spring容器中获得FreeMarkerConfigurer对象
2、从FreeMarkerConfigurer对象中获得Configuration对象
3、使用Configuration对象获得Template对象
4、创建数据集
5、创建输出文件的Writer对象
6、调用模板对象的process方法,生成文件
7、关闭流
@Controller
public class HtmlGenController {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@RequestMapping("/genhtml")
@ResponseBody
public String genHtml() throws Exception {
//生成静态页面
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Template template = configuration.getTemplate("hello.ftl");
Map data = new HashMap<>();
data.put("hello", "spring freemarker test");
Writer out = new FileWriter(new File("D:/temp/javaee28/out/test.html"));
template.process(data, out);
out.close();
//返回结果
return "OK";
}
}