Use Freemarker view
Spring Boot default to Freemarker also supported the need yo use Freemarker first step is to add Freemarker dependent.
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration
Freemarker responsible for automatic configuration. The default Freemarker will classpath:/templates/
find the template in the path, and the default view will be added after the name .ftl
suffix, that is, when the view name returned is abc, the return of Freemarker template file is classpath:/templates/abc.ftl
. It is assumed that the following Controller, when accessed /freemarker/hello
when the return classpath:/templates/hello.ftl
template file.
@Controller
@RequestMapping("freemarker")
public class FreemarkerController {
@GetMapping
public String index() {
return "index";
}
@GetMapping("hello")
public String hello(Map<String, Object> model) {
model.put("message", "helloWorld!");
model.put("list", Arrays.asList(10, 20, 30, 40, 50));
return "hello";
}
}
If the hello.ftl
content is as follows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello Freemarker</title>
</head>
<body>
Hello Freemarker!
<br/>
${message}
<ul>
列表元素是:
<#list list as item>
<li>${item}</ >Li
</#list>
</ul>
</body>
</html>
When you visit /freemarker/hello
you will see something like this.
If you do not want to use the default template path, can spring.freemarker.templateLoaderPath
be specified properties, it can specify multiple paths simultaneously. It can also spring.freemarker.prefix
prefix template designated by spring.freemarker.suffix
the suffix specified template. These properties will be responsible for receiving FreeMarkerProperties. When we specify the following configuration, the view name if the return is abc, then look for classpath:/freemarker/prefix/abc.ftl
or classpath:/ftl/prefix/abc.ftl
.
spring.freemarker.templateLoaderPath=classpath:/freemarker/,classpath:/tpl/
spring.freemarker.prefix=prefix/
spring.freemarker.suffix=.ftl
(Note: This article is written based on Spring Boot 2.0.3)