Spring Boot(24)——使用Freemarker视图

使用Freemarker视图

Spring Boot默认对Freemarker也有支持,需哟使用Freemarker的第一步是加入Freemarker的依赖。

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration负责对Freemarker进行自动配置。默认Freemarker将在classpath:/templates/路径下寻找模板,且默认将在视图名称后加上.ftl后缀,即当返回的视图名称是abc时,返回的Freemarker模板文件是classpath:/templates/abc.ftl。现假设有如下Controller,当访问/freemarker/hello时将返回classpath:/templates/hello.ftl模板文件。

@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";
  }

}

如果hello.ftl的内容如下。

<!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>

那么当访问/freemarker/hello时你将看到如下内容。

freemarker结果

如果不想使用默认的模板路径,可以通过spring.freemarker.templateLoaderPath属性进行指定,它可以同时指定多个路径。它也可以通过spring.freemarker.prefix指定模板的前缀,通过spring.freemarker.suffix指定模板的后缀。这些属性将由FreeMarkerProperties负责接收。当我们指定了如下配置时,如果返回的视图名称是abc,则将寻找classpath:/freemarker/prefix/abc.ftlclasspath:/ftl/prefix/abc.ftl

spring.freemarker.templateLoaderPath=classpath:/freemarker/,classpath:/tpl/
spring.freemarker.prefix=prefix/
spring.freemarker.suffix=.ftl

(注:本文基于Spring Boot 2.0.3所写)

猜你喜欢

转载自elim.iteye.com/blog/2441921