SpringBoot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖。
SpringBoot支持多种模版引擎包括:
Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
Thymeleaf特性如下:
application.yml中可以配置thymeleaf模板解析器属性如下:
#THYMELEAF (ThymeleafAutoConfiguration) #开启模板缓存(默认值:true) spring.thymeleaf.cache=true #Check that the template exists before rendering it. spring.thymeleaf.check-template=true #检查模板位置是否正确(默认值:true) spring.thymeleaf.check-template-location=true #Content-Type的值(默认值:text/html) spring.thymeleaf.content-type=text/html #开启MVC Thymeleaf视图解析(默认值:true) spring.thymeleaf.enabled=true #模板编码 spring.thymeleaf.encoding=UTF-8 #要被排除在解析之外的视图名称列表,用逗号分隔 spring.thymeleaf.excluded-view-names= #要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5) spring.thymeleaf.mode=HTML5 #在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ #在构建URL时添加到视图名称后的后缀(默认值:.html) spring.thymeleaf.suffix=.html #Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。 spring.thymeleaf.template-resolver-order= #可解析的视图名称列表,用逗号分隔 spring.thymeleaf.view-names=
引入thymeleaf依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
application.yml文件中添加thymeleaf模板配置:
##添加thymeleaf模板配置 spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html
在resources/static/css文件夹下添加main.css样式文件,内容如下:
h1 {
color: #0000FF;
}
h2 {
color: #FF0000;
}
在resources/templates文件夹下添加index.html样式文件,内容如下:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<!-- xmlns:th 引入 thymeleaf(缩写为 th) 命名空间,模板文件中的动态属性可以用 th:xxx 指定 -->
<head>
<title>Spring Boot + Thymeleaf demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" th:href="@{/style/main.css}"/>
<!-- @{path} 引用 /static 下的静态资源文件 -->
</head>
<body>
<h1>Spring Boot + Thymeleaf demo</h1>
<h2 th:text="‘Message: ‘ + ${message}"></h2>
<!-- ${xxx} 引用 SpringMVC 中 model 属性 -->
</body>
</html>
创建一个HelloController.java,内容如下:
@Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(method= RequestMethod.GET,produces="text/html;charset=UTF-8") public String hello(Map<String, Object> model) { model.put("message", "Hello World!"); return "index"; // templates\index.html } }
最后在DemoApplication就可以访问。
项目结构图如下:
原文:https://www.cnblogs.com/bl123/p/14357268.html