【SpringBoot系列02】SpringBoot之使用Thymeleaf视图模板

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xp541130126/article/details/81632144

前言

Thymeleaf 是Java服务端的模板引擎,与传统的JSP不同,前者可以使用浏览器直接打开,因为可以忽略掉拓展属性,相当于打开原生页面,给前端人员也带来一定的便利。如果你已经厌倦了JSP+JSTL的组合,Thymeleaf或许是个不错的选择!

一、目标

使用thymeleaf视图模板,并且于SpringBoot进行整合。

二、实现

首先创建一个SpringBoot项目,添加如下依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- springboot web 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- thymeleaf 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

添加完依赖以后,就需要编写对应的Controllerview

resource目录下新建templates文件夹并且在该目录下新建文件index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>你好</h1>
    <h1 th:text="${name}">  </h1>
</body>
</html>

src/main/java/com/yukong/chapter目录下新建IndexController

@Controller
public class IndexController {

    @GetMapping("/hello")
    public String hello(@RequestParam(defaultValue = "world", required = false) String name, Model model) {
        model.addAttribute("name", name);
        return "index";
    }

}

注意这里使用的是@Controller

然后在src/resource/application.yml配置一下thymeleaf相关配置


server:
  port: 8989
spring:
  thymeleaf:
    # 配置视图路径前缀
    prefix: classpath:/templates/
    # 配置视图路径后缀
    suffix: .html
    mode: html
    # 关闭缓存 修改视图 刷新浏览器就显示 开发阶段务必关闭缓存 (=false)
    cache: false

启动Chapter21Application.java并且访问http://localhost:8989/hello

结果如图:

image.png

扫描二维码关注公众号,回复: 4388938 查看本文章

再次访问http://localhost:8989/hello?name=yukong
结果如图
image.png

三、总结

此致我们SpringBoot整合thymeleaf就完毕了。
最后配套教程的代码全部在这里
github https://github.com/YuKongEr/SpringBoot-Study

猜你喜欢

转载自blog.csdn.net/xp541130126/article/details/81632144
今日推荐