SpringBoot通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行自动配置。
第一步:在pom.xml文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
第二步:在application.properties配置文件中对默认设置进行修改,如下:
# thymeleaf相关配置参数 (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
这样我们就配置完成了,可以在*.html文件中进行使用啦~~
接下来!!!
在SpringBoot中使用Thymeleaf的小案例(通过Controller成功访问静态资源和模板页面)
以在浏览器中访问登录页面为例:
1. 静态资源架构图:
2. login.html文件如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>登录页 | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" th:href="@{admin/dist/img/favicon.png}"/>
<!-- Font Awesome -->
<link rel="stylesheet" th:href="@{admin/dist/css/font-awesome.min.css}">
<!-- Ionicons -->
<link rel="stylesheet" th:href="@{admin/dist/css/ionicons.min.css}">
<!-- Theme style -->
<link rel="stylesheet" th:href="@{admin/dist/css/adminlte.min.css}">
<style>
canvas {
display: block;
vertical-align: bottom;
}
#particles {
background-color: #F7FAFC;
position: absolute;
top: 0;
width: 100%;
height: 100%;
z-index: -1;
}
</style>
</head>
<body class="hold-transition login-page">
div class="login-box">
......
......
......(登录页面具体布局省略......)
......
......
</div>
<!-- /.login-box -->
<!-- jQuery -->
<script th:src="@{admin/plugins/jquery/jquery.min.js}"></script>
<!-- Bootstrap 4 -->
<script th:src="@{admin/plugins/bootstrap/js/bootstrap.bundle.min.js}"></script>
</body>
</html>
3. IndexController.java文件如下:(当然,获取登录页面的方式不止作者写的这一种,网上都可以找到的,本人就不赘述了)
package zqq.trys.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @Auther: zhangqingqing
* @Date: 2019/12/24 11:32
* @Description:
*/
@Controller
public class IndexController{
/**
* 登录页面
*
* @return
*/
@RequestMapping("/loginPage")
public ModelAndView getSidebarPage() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("admin/login");
return modelAndView;
}
}
4. 通过网址:http://localhost:8082/loginPage来访问,效果图如下:(端口8082是本人在application.properties中配置的,也可以配置为其它。)