1. 前言
所谓的模板引擎,便是将模板和数据模型渲染成输出文件。
FTL + Java POJO = HTML
2. 实现
2.1 添加依赖
在你搭建的Web
项目中,添加starter-freemarker
依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.2 添加yml
配置
在你的application.yml
中再添加freemarker
的配置。
spring:
freemarker:
suffix: .ftl
cache: false
charset: UTF-8
2.3 定义模板
2.3.1 head.ftl
先创建一个头部公共模板,用来给其他模板页面引用。
文件路径:src\main\resources\templates\common\head.ftl
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>spring-boot-template-freemarker</title>
</head>
2.3.2 login.ftl
定义一个登陆页面模板,引入head.ftl
。
引入方式:<#include "../common/head.ftl">
文件路径:src\main\resources\templates\page\login.ftl
<!doctype html>
<html lang="en">
<#include "../common/head.ftl">
<body>
<div id="app" style="margin: 20px 20%">
<form action="/demo/user/login" method="post">
用户名<input type="text" name="name" placeholder="用户名"/>
密码<input type="password" name="password" placeholder="密码"/>
<input type="submit" value="登录">
</form>
</div>
</body>
</html>
2.3.2 index.ftl
登陆成功后,给个首页让它跳转。然后在首页显示登陆的用户名称。
获取用户名称的方式:${user.name}
。这个值是在后台Contrller
设置的,后面会介绍。
定义一个首页页面模板,引入head.ftl
。
文件路径:src\main\resources\templates\page\login.ftl
<!doctype html>
<html lang="en">
<#include "../common/head.ftl">
<body>
<div id="app" style="margin: 20px 20%">
欢迎登录,${user.name}!
</div>
</body>
</html>
2.4 Controller
用户的请求,由Controller
接收,然后准备模型数据,将数据渲染到模板,最终输出静态页面给用户。
数据渲染的过程,Spring
已经封装好了。我们只要把数据模型准备好,然后返回指定的模板就行了。
下面看看如何在Controller
中准备数据和指定模板吧。
@Controller
@RequestMapping("/user")
public class UserController {
//将登录页面返回给用户
@GetMapping("/login")
public ModelAndView login() {
//直接在ModelAndView中指定登录模板的路径
return new ModelAndView("page/login");
}
//用户点击登录,POST方式提交表单,跳转首页
@PostMapping("/login")
public ModelAndView login(User user, HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
//准备模型数据
mv.addObject(user);
//redirect:表示重定向到某个页面,/ 代表首页,在IndexController定义了这个路径
mv.setViewName("redirect:/");
request.getSession().setAttribute("user", user);
return mv;
}
}
@Controller
public class IndexController {
@GetMapping(value = {"", "/"})
public ModelAndView index(HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
User user = (User) request.getSession().getAttribute("user");
if (ObjectUtil.isNull(user)) {
mv.setViewName("redirect:/user/login");
} else {
mv.setViewName("page/index");
mv.addObject(user);
}
return mv;
}
}
3.扩展
更多FTL语法糖请详见:Freemarker中文参考手册