创建freemarker模板
在src/java/resources目录下创建templates文件夹并创建demo.ftl。模板默认是从【classpath:/templates/】这个位置查找的。
添加依赖:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.27-incubating</version>
</dependency>
添加配置(如果必要,我下面的demo代码是没有),在application.properties:
spring.freemarker.allow-request-override=false
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
编写controller类:
@Controller
public class FreemarkerController {
@Autowired
Configuration configuration;
/**
* 创建freemarker模板
* 在src/java/resources目录下创建templates文件夹并创建demo.ftl。
* 模板默认是从【classpath:/templates/】这个位置查找的。
* @param map
* @return
*/
@RequestMapping("/demo2")
public String demo(Map<String, Object> map) {
map.put("descrip", "It's a springboot integrate freemarker's demo!!!!");
return "demo";
}
/**
* 测试FreeMarker魔板2
* @throws IOException
* @throws ParseException
* @throws MalformedTemplateNameException
* @throws Exception
*/
@RequestMapping("/test2")
public void demo2(HttpServletRequest request, HttpServletResponse response) throws Exception{
Map<String, Object> model = new HashMap<String, Object>();
model.put("time", new Date());
model.put("message", "这是测试的内容。。。");
model.put("toUserName", "张三");
model.put("fromUserName", "老许");
Template t = configuration.getTemplate("welcome.ftl"); // freeMarker template
String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
response.setContentType("text/html; charset=" + t.getEncoding());
Writer out = response.getWriter();
//合并数据模型和模版,并将结果输出到out中
t.process(model, out);
System.out.println(content);
//return content;
}
}
魔板路径以及代码: src/main/resource/templates/demo.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
请看说明:${descrip} <br />
haahaaaa
</body>
</html>
src/main/resource/templates/welcome.ftl
<!DOCTYPE html>
<html>
<body>
<h4>亲爱的${toUserName},你好!</h4>
<p style="color:blue;"> ${message}</p>
祝:开心!
</br>
${fromUserName}
</br>
${time?date}
</body>
</html>
到此为止, 已经完成, 运行此项目.
访问:
http://localhost:8083/test2
结果是:
访问:
http://localhost:8083/demo2
结果: