SpringBoot 使用 freemarker 模板引擎
快速构建freemarker 模板引擎
简单5步起,就实现模板引擎开始:
- 1、引入依赖包。
- 2、设置配置文件。
- 3、编辑后台代码。
- 4、编辑前端代码。
- 5、启动项目访问。
构建步骤
1、SpringBoot 的 pom.xml 引入 freemarker 依赖包
SpringBoot默认提供了freemarker的Starter,只需简单引入依赖即可。
org.springframework.boot spring-boot-starter-freemarker
版本号根据SpringBoot的版本号,引用的版本不一样。本教程使用SpringBoot 2.1.5.RELEASE 版本,默认使用2.3.28版本。
2、SpringBoot 设置配置文件
本教程使用了yml来配置SpringBoot的配置文件,使用三个配置文件。开发环境和生产环境都需要添加。配置文件可以参考:
spring: #模板配置 freemarker: allow-request-override: false cache: false #是否开启缓存,生成环境建议开启 check-template-location: true charset: UTF-8 #编码 content-type: text/html; charset=utf-8 #content-type类型 expose-request-attributes: false #设定所有request的属性在merge到模板的时候,是否要都添加到model中 expose-session-attributes: false #设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中. expose-spring-macro-helpers: false #RequestContext属性的名称 suffix: .html #模板后缀 template-loader-path: classpath:/theme/fm #模版存放路径 # allow-session-override: false # 是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。 # enabled: true # 是否为此技术启用MVC视图解析。 # prefer-file-system-access: true # 通过文件系统访问,可以热检测模板更改。 # prefix: # 前缀,用于在构建URL时查看名称。 # request-context-attribute: # 所有视图的RequestContext属性的名称。 # settings.*: # 众所周知的FreeMarker密钥,这些密钥已传递到FreeMarker的配置中。 # view-names: # 可以解析的视图名称的白名单。
3、SpringBoot 编辑后台代码
实现一个文章来当例子:
package com.mainboot.mainbootAdmin.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.mainboot.mainbootAdmin.model.Article; import com.mainboot.mainbootAdmin.service.ArticleService; @Controller @RequestMapping("article") public class ArticleViewController { @Autowired private ArticleService articleService; @RequestMapping("index") public String index(Integer id,Model mv){ Article article = new Article(); if(id!=null){ article = articleService.findId(id); } mv.addAttribute("article", article); return "index"; } }
4、SpringBoot 编辑前端代码
${article.title}
${article.info}
5、SpringBoot 启动项目访问
运行项目:访问:url/article/index?id=3056