继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

富国沪深
关注TA
已关注
手记 294
粉丝 41
获赞 158

前言

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

@Controllerpublic 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

结果如图:

webp

image.png

再次访问http://localhost:8989/hello?name=yukong

结果如图


webp

image.png



作者:余空啊
链接:https://www.jianshu.com/p/66d1be96ea1e


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP