Spring Boot 集成 FreeMarker

时间:2019-11-13
本文章向大家介绍Spring Boot 集成 FreeMarker,主要包括Spring Boot 集成 FreeMarker使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用 FreeMarker 作为页面展示

FreeMarker是一种比较简单的网页展示技术,是网页模板和数据模型的结合体。这种结合模式的好处就是,分离了网页界面设计人员和编程人员的工作,让他们各司其职。

一、build.gradle 中增加 FreeMarker 依赖:

    compile "org.springframework.boot:spring-boot-starter-freemarker"

二、src/main/resources 中创建 application.properties 文件,内容如下:

spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request

或在application.yml中增加配置:

spring:
  datasource:
        url: jdbc:mysql://172.17.7.XXX:3306/Exfresh_XXX
        username: ygtest
        password: ygtest
  freemarker:
         allow-request-override: false
         cache: false
         check-template-location: true
         charset: UTF-8
         content-type: text/html; charset=utf-8
         expose-request-attributes: false
         expose-session-attributes: false
         expose-spring-macro-helpers: false
         suffix: .ftl
         template-loader-path: classpath:/templates/

三、src/main/resources 创建目录 templates, 并在此目录创建 hello.ftl,内容如下:

<!DOCTYPE html>

<html lang="en">

<body>
Date: ${time?date}
<br>
Time: ${time?time}
<br>
Message: ${message}
</body>

</html>

四、修改 HelloController.java:

package cn.zss.zsdemo.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

@Controller
public class HelloController {

    @Value("${application.message:Hello World}")
    private String message = "Hello World";

    @RequestMapping("/hello")
    public String welcome(ModelMap model){
        model.put("time",new Date());
        model.put("message",this.message);
        return "hello";
    }
}

使之前 @ResponseBody 输出改成 freemarker 页面输出,并从 application.properties 取值填充页面。

五、启动应用,浏览器打开 http://localhost:8080/hello 查看页面展示:

原文地址:https://www.cnblogs.com/jerrys/p/11847190.html