前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【SpringBoot系列02】SpringBoot之使用Thymeleaf视图模板前言一、目标二、实现三、总结

【SpringBoot系列02】SpringBoot之使用Thymeleaf视图模板前言一、目标二、实现三、总结

作者头像
yukong
发布2018-08-21 10:19:52
3370
发布2018-08-21 10:19:52
举报
文章被收录于专栏:yukong的小专栏yukong的小专栏

前言

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

一、目标

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

二、实现

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

代码语言:javascript
复制
 <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

代码语言:javascript
复制
<!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

代码语言:javascript
复制
@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相关配置

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

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

结果如图:

image.png

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

结果如图

image.png

三、总结

此致我们SpringBoot整合thymeleaf就完毕了。

本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.08.13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 一、目标
  • 二、实现
  • 三、总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com