SpringBoot集成thymeleaf
1.首先pom文件中已经有spring-boot-starter-parent与spring-boot-starter-web配置。
2.在pom文件中加入以下依赖
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.在中添加一下配置
=UTF-8
-type=text/html
=LEGACYHTML5
#开发时关闭缓存,不然没法看到实时页面
=false
4.在resources下创建templates文件夹,在该文件夹下创建html文件即可。
thymeleaf页面模板
<!DOCTYPE html>
<html lang="en" xmlns:th="">
<head>
<meta charset="UTF-8"/>
<title>thymeleaf template</title>
</head>
<body>
<h1>Thymeleaf模板文件</h1>
</body>
</html>
公共页面元素的抽取
1.首先写一个,内容如下,其中要加入的js,css可以根据自己的需求添加
<head th:fragment="commonHead(title)">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title th:text="${title}">Title</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- jquery ui组件引用 提示框-->
<link rel="stylesheet" type="text/css" th:href="@{/common/jquery-ui-1.11.4/}" />
<!-- jquery组件引用 -->
<script th:src="@{/common/jquery/jquery-1.12.}"></script>
<script type="text/javascript">
// 项目路径
/* var ctx = "${}"; */
var ctx = "/projectName";
</script>
</head>
其中引入的静态资源在resources/static/common/jquery目录下,在resources/templates目录下
2.在其他页面中使用上面所创建的
<!DOCTYPE html>
<html lang="en" xmlns:th="">
<head th:replace="head :: commonHead('验证公共静态资源的引入')"></head>
<body>
<h1>Thymeleaf模板文件</h1>
</body>
</html>
其中<head th:replace="head :: commonHead('验证js')"></head>中的head对应的名字,commonHead对应中的th:fragment="commonHead(title)"
默认页面
在没有设置默认页面,在地址栏输入http://ip:端口号(eg:localhost:8080,springboot项目默认访问路径为"/",访问时直接使用http://ip:端口号,但是可以指定访问路径,如果指定了访问路径,访问时要带*问路径:http://ip:端口号/访问路径,eg:localhost:8080/demo)时访问页面出错,下面设置默认页面
方法一:在controller中写一个类,如下:
import ;
import ;
import ;
import ;
@Controller
public class IndexController {
@RequestMapping("/")
public String index(Model model, HttpServletResponse response) {
("name", "simonsfan");
return "index";
}
}
方法二:新建一个DefaultViewController类,如下:
import ;
import ;
import ;
import ;
@Configuration
public class DefaultViewController extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
("/").setViewName("index");
(Ordered.HIGHEST_PRECEDENCE);
(registry);
}
}
模板页面实时生效
1、禁用模板引擎的缓存:=false
2、页面修改后ctrl+F9