springboot整合thymeleaf

开始整合

在以往的开发中往往使用JSP进行页面开发,但是在springboot中已经不推荐使用JSP了,推荐使用模板引擎进行页面渲染,在本文中将整合thymeleaf模板引擎

修改pom文件,添加依赖

将以下依赖添加到pom文件中

<!-- thymeleaf支持 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

修改application.yml的配置

配置application.yml文件,注意每一项配置的键和值之间有空格,不同级别的配置需要缩进

spring:
  thymeleaf:
    encoding: utf-8
    suffix: .html
    cache: false #开发过程中关闭缓存
    mode: LEGACYHTML5 #thymeleaf语法检查过于严格,通过此项关闭

在controller中添加测试方法

/**
* 前往thymeleaf模板引擎渲染的主页,模板页面放在resources/templates下
* 请求地址为http://localhost:8080/
*/
@GetMapping("/")
public String testThymeleaf(Model model){
    //设置两个参数传入到模板引擎
    //第一个参数是键 第二个参数是值
    model.addAttribute("str","字符串");
    model.addAttribute("bool",false);
    model.addAttribute("list", Arrays.asList(1,2,3,4,5));
    //指定模板为templates文件夹下的index.html
    return "index.html";
}

添加模板页面

在resources/templates下添加模板页面
thymeleaf模板页面
页面代码如下

<!DOCTYPE html>
<html lang="zh-Hans" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>thymeleaf-测试</title>
    </head>

    <body>
        <h1>thymeleaf-测试</h1>

        <h2>controller传入字符串参数:</h2>
        <!-- 通过类似JSP的EL表达式把值取出来 -->
        <div th:text="${str}"></div>

        <h2>thymeleaf条件判断:</h2>
        bool的值为:
        <span th:if="${bool}">true</span>
        <span th:unless="${bool}">false</span>

        <h2>thymeleaf循环遍历list集合:</h2>
        <!-- 循环遍历list集合 -->
        <ul>
            <li th:each="temp : ${list}" th:text="${temp}"></li>
        </ul>

    </body>
</html>

启动程序在浏览器中访问 http://localhost:8080/ ,界面如下
thymeleaf页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值