SpringBoot整合Thymeleaf模板引擎

一、创建工程,添加依赖

首先,创建一个SpringBoot工程,然后添加spring-boot-starter-webspring-boot-starter-thymeleaf依赖,代码如下:

       <!-- 实现web功能 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 模版 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

二、配置Thymeleaf文件

2.1 yml的写法

使用yml配置Thymeleaf的参数进行自定义配置,如下:


server:
    # 端口
    port: 8081
spring:
    # 数据源配置
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3307/spring?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&useSSL=false
        username: "root"
        password: "001314"
        hikari:
            # 连接池名
            pool-name: DateHikariCP
            # 最小空闲连接数
            minimum-idle: 5
            # 空闲连接存活最大时间,默认600000(10分钟)
            idle-timeout: 180000
            # 最大连接数,默认10
            maximum-pool-size: 10
            # 从连接池返回的连接的自动提交
            auto-commit: true
            # 连接最大存活时间,0表示永久存活,默认1800000(30分钟)
            max-lifetime: 1800000
            # 连接超时时间,默认30000(30秒)
            connection-timeout: 30000
            # 测试连接是否可用的查询语句
            connection-test-query: SELECT 1

    thymeleaf:
        # 是否开发缓存,开发时可设置为false,默认true
        cache: false
        # 检查模板是否存在,默认true
        check-template: true
        # 模板文件编码
        encoding: UTF-8
        # 模板文件位置
        prefix: classpath:/templates/
        # 模板文件后缀
        suffix: .html
        # content-type配置
        servlet:
            content-type: text/html


2.2 properties的写法


# 启用模板缓存(开发时建议关闭)
spring.thymeleaf.cache = true
# 检查模板是否存在,然后再呈现 
spring.thymeleaf.check-template = true
# 检查模板位置是否存在  
spring.thymeleaf.check-template-location = true
# Content-Type值   
spring.thymeleaf.content-type = text/html
# 启用MVC Thymeleaf视图分辨率
spring.thymeleaf.enabled = true
# 模板编码
spring.thymeleaf.encoding = UTF-8
# 在构建URL时预先查看名称的前缀    
spring.thymeleaf.prefix = classpath:/templates/
# 构建URL时附加查看名称的后缀 
spring.thymeleaf.suffix = .html    

三、配置控制器

创建Book实体类,下面使用了Lombok的写法,使用前需要安装插件,Lombok可以简化代码,少写gettersetter方法等方法

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {

    private Integer bookID;
    private String bookName;
    private int bookCounts;
    private String bookSummary;
}

编写Controller类

@Controller
public class HelloController {
    @RequestMapping("/books")
    public String greeting(Model model){
    	String str = "学习SpringBoot整合Thymeleaf";
        model.addAttribute("desc",str);
        return "inddex";
    }
}

在Controller类中使用了注解,@RequestMapping,那么此注解和@GetMapping有什么不同呢?
经过查看SpringBoot的源代码发现,在GetMapping的方法中有@RequestMapping,所以,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

注意@RequestMapping如果没有指定请求方式,将接收Get、Post、Head、Options等所有的请求方式。

templates文件夹下创建index.html的文件。


重要:如果使用Thymeleaf,加载数据,则需要使用标签:
<html xmlns:th="http://www.thymeleaf.org">


index.html的文件内容如下:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <!--/*@thymesVar id="name" type="java.lang.String"*/-->
    <p th:text="'Hello!, ' + ${desc} + '!'"></p>
</body>
</html>

运行项目,访问:
http://localhost:8080/books,即可看到Controller中的那句字符串,学习SpringBoot整合Thymeleaf

3.1 扩展Thymeleaf知识

Thymeleaf的基础语法

  1. 创建HTML,需要添加以下内容
<html xmlns:th="http://www.thymeleaf.org">
  1. 获取变量值
<p th:text="'Hello!, ' + ${desc} + '!'"></p>
  1. 链式表达式
    用来配合link src href使用的语法,类似的标签有:th:hrefth:src
<link th:src="@{/css/style.css}">
<a href="login.html" th:href="@{/views/login.html}"></a>
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<img th:src="@{/images/1.png}">
  1. 文本替换
<span th:text="'Welcome to our SpringBoot, ' + ${user.name} + '!'">
  1. 条件
    if、unless
    使用th:ifth:unless属性进行条件判断,th:unlessth:if恰好相反,只有表达式中的条件不成立,才会显示其内容。
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

switch

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>
  1. 循环
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>

    <p th:text="'Hello ' + (${name}?:'admin')">3333</p>
    <table>
        <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>AGE</th>
        </tr>
        <!--empList是控制层addAtributes中的值 -->
        <tr th:each="emp : ${empList}">
            <td th:text="${emp.id}">1</td>
            <td th:text="${emp.name}">王菜鸟</td>
            <td th:text="${emp.age}">18</td>
        </tr>
    </table>
</body>
</html>

3.2 常用标签

在这里插入图片描述







以下部分是做登录功能的拦截器!!!

四、配置拦截器

4.1 自定义映射资源

重写 WebMvcConfigurerAdapter 中的 addViewControllers 方法即可达到你想要的处理效果
在Config的配置文件中,定义WebMvcConfiguration重写

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        // 映射为 user 的控制器下的所有映射
 		registry.addViewController("/").setViewName("index");
		registry.addViewControllers("/index.html").setViewName("index");
    }
}

4.2 拦截器addInterceptors

拦截器在项目中经常使用的,这里介绍下最简单的判断是否登录的使用。
要实现拦截器功能需要完成2个步骤:

创建自己的拦截器类并实现 HandlerInterceptor 接口
重写WebMvcConfigurerAdapter类中的addInterceptors方法把自定义的拦截器类添加进来即可

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect("/index");
            return false;
        } else {
            return true;
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值