Spring Boot (24) - Use view Freemarker

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.FreeMarkerAutoConfigurationFreemarker 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 .ftlsuffix, 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/hellowhen the return classpath:/templates/hello.ftltemplate 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.ftlcontent 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/helloyou will see something like this.

freemarker results

If you do not want to use the default template path, can spring.freemarker.templateLoaderPathbe specified properties, it can specify multiple paths simultaneously. It can also spring.freemarker.prefixprefix template designated by spring.freemarker.suffixthe 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.ftlor 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)

Guess you like

Origin elim.iteye.com/blog/2441921