一、配置Thymeleaf
1.简介
Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。
Thymeleaf的主要目标是提供一个优雅和高度可维护的创建模板的方式。为了实现这一点,它建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型。这改善了设计的沟通,弥合了设计和开发团队之间的差距。
Thymeleaf也从一开始就设计了Web标准 - 特别是HTML5 - 允许您创建完全验证的模板,如果这是您需要的。
thymeleaf解析原理: thymeleaf在指定的模式下处理文件之前会首先将文件转换为格式良好的XML文件,而此XML文件仍然是完全有效的HTML5;解析xml方式为SAX,Html页面要求严格格式,一定要有封闭标签:/> 或 </>
2.pom文件加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.在application.properties文件中增加Thymeleaf模板的配置。
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
在开发时建议将spring.thymeleaf.cache设置为false,否则会有缓存,导致页面没法及时看到更新后的效果。
比如你修改了一个文件,已经update到tomcat,但刷新页面还是之前的页面,就是因为缓存引起的。
4.创建一个Controller
@RequestMapping(value = "/hello")
public ModelAndView test() {
ModelAndView mv = new ModelAndView();
mv.setViewName("/hello");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
5.编写模版文件src/main/resouces/templates/hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello.v.2</h1>
<p th:text="${title}"></p>
</body>
</html>
6.启动应用,输入地址:http://127.0.0.1:8080/hello
二、freemarker配置
1.pom加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.application配置文件
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/#comma-separatedlist
#spring.freemarker.view-names= #whitelistofviewnamesthatcanberesolved
3.创建Controller
@RequestMapping("/hello")
public String helloFtl(Map<String,Object> map){
map.put("hello","Hello!");
return"/hello";
}