一、整合Thymeleaf
Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,FreeMaker等, 它也可以轻易的与 Web 框架进行集成作 为 Web 应用的模板引擎。与其它模板引擎相比, Thymeleaf 最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要 启动整个Web应用。 thymeLeaf支持Spring Expression Language语言作为方言,也就是SpEL,SpEL是可以用于Spring中的一种EL表达式。它与我们使用 过的JSP不同,thymeleaf是使用html的标签来完成逻辑和数据的传入进行渲染。 可以说用 thymeleaf 完全替代 jsp 是可行的
1.创建项目添加web依赖和Thymeleaf模板引擎依赖
2.Thymeleaf 配置
2.1 Spring Mvc 视图解析器配置
修改 application .properties加入如下代码
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
3.测试
1.创建 hello.html
在templates下创建一个hello.html 必须加入xmlns:th="http://www.thymeleaf.org" Thymeleaf声明空间
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎</h1>
<p th:text="${username}"></p>
</body>
</html>
2 创建 HelloController
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String thrmeleaf(Model model){
model.addAttribute("username","zhangsan");
return "index";
}
}
3.访问测试
二、整合 Freemarker
1.创建项目添加web依赖和Freemarker模板引擎依赖
2.Freemarker 配置
2.1 Spring Mvc 视图解析器配置
#freemarker
spring.freemarker.template-loader-path=classpath:/templates/
# 后缀
spring.freemarker.suffix=.html
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
3.测试
1 创建 hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>${username}</h1>欢迎使用Freemarker模板
</body>
</html>
2.创建Controller
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model){
model.addAttribute("username","张三");
return "hello";
}
}
3.访问测试