1. pom 文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2. 接下来是freemarker的一些基本设置,包括他的ftl文件路径,也就是他的模板路径,我在resources下templates下,后边是application.properties中的设置:
spring.freemarker.suffix=.ftl spring.freemarker.templateEncoding=UTF-8 spring.freemarker.templateLoaderPath=classpath:/templates/ spring.freemarker.content-type=text/html
例如,我们添加一个模板文件,叫做 welcome.ftl。
<!DOCTYPE html>
<html lang="en">
<body>
Date: ${time?date}<br>
Message: ${message}
</body>
</html>
@RestController("template.freemarkerController2")
@EnableAutoConfiguration
public class Welcome2Controller {
@Autowired
private Configuration configuration;
@RequestMapping("/template/freemarker/welcome2")
public String welcome2(Map model) throws Exception {
model.put("time", new Date());
model.put("message", "梁桂钊");
Template template = configuration.getTemplate("welcome.ftl");
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
FileUtils.writeStringToFile(new File("d:/welcome.html"), content);
return "welcome";
}
}
我这次做的是xml 的模板,开始怎么都不好使。后来去掉xml 头部<?xml 这行就可以了