SpringBoot实战教程(5)| 整合Freemaker

        FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

Freemarker中文手册: FreeMarker 中文官方参考手册

目录

一、初始化Springboot项目

二、引入依赖文件

三、编写配置文件

四、编写Controller类

五、编写模板文件

 六、预览效果


一、初始化Springboot项目

二、引入依赖文件

    <!--   freemarker    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!--    web     -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        

三、编写配置文件

application.yml

# freemarker模板引擎
spring:
  freemarker:
    allow-request-override: true
    allow-session-override: true
    # 是否开始缓存
    cache: false
    check-template-location: true
    # 默认编码格式
    charset: UTF-8
    content-type: text/html;
    expose-request-attributes: true
    expose-session-attributes: true
    expose-spring-macro-helpers: true
    # 模板放置位置
    template-loader-path: classpath:/templates/
    # 文件目录前缀
    prefix:
    # 文件后缀
    suffix: .ftl
    request-context-attribute: request
    settings:
      template_update_delay: 0
      url_escaping_charset: UTF-8
      locale: UTF-8
      # 日期时间格式化
      datetime_format: yyyy-MM-dd HH:mm:ss
      # 日期格式化
      date_format: yyyy-MM-dd
      # 时间格式化
      time_format: HH:mm:ss
      template_exception_handler: html_debug
      # 数字格式化,无小数点
      number_format: '0.#'
      # 设置freemarker标签 0,1,2 0=自动识别,默认1
      tag_syntax: 'auto_detect'

四、编写Controller类

IndexController.java

package com.csdn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexController {

    @GetMapping("/index")
    public String index(ModelMap model) {
        Map<String, Object> info = new HashMap<>();
        info.put("name", "Roc-xb");
        info.put("age", "25");
        info.put("date", "2021年12月10日19:48:01");
        model.put("info", info);
        return "index";
    }
}

五、编写模板文件

index.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>freemaker测试页面</title>
</head>
<body>
 <div>${info.name}</div>
 <div>${info.age}</div>
 <div>${info.date}</div>
</body>
</html>

 六、预览效果

作者:YangRoc

出处:https://www.cnblogs.com/YangRoc/p/17186427.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   Roc-xb  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

易微帮源码


易微帮官网

more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示