美文网首页从零开始学springboot
从零开始学springboot-整合thymeleaf

从零开始学springboot-整合thymeleaf

作者: 码哥说 | 来源:发表于2019-03-20 16:14 被阅读0次

前言

上一节使用了"过时"的jsp技术,这一节我们来使用springboot推荐的模板thymeleaf技术。

创建项目

使用IDEA创建springboot项目,直接勾选web和thymeleaf依赖


1.png

查看依赖

2.png

添加配置

application.yml:

spring:
  thymeleaf:
    mode: HTML5
    encoding: UTF-8
    ##关闭缓存
    cache: false

添加模板

在resources的templates下创建index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
<head>
    <meta charset="utf-8"/>
</head>
<body>
<span th:text="'yes, ' + ${name} + '!'"></span>
</body>
</html>

注意,这里模板内注入了个变量"name",模板都是使用"${变量名}"这种方式注入变量的。

完善

目录结构

3.png

controller/IndexController:

package com.mrcoder.sbthymeleaf.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping(value = "/")
    public String index(Model model){
        //注入name变量到模板
        model.addAttribute("name", "hello world");
        return "index";
    }
}

访问

4.png

关于thymeleaf的更多语法请自行去看官方文档哦。

项目地址

https://github.com/MrCoderStack/SpringBootDemo/tree/master/sb-thymeleaf

https://gitee.com/MrCoderStack/SpringBootDemo/tree/master/sb-thymeleaf

请关注我的订阅号

订阅号.png

相关文章

网友评论

    本文标题:从零开始学springboot-整合thymeleaf

    本文链接:https://www.haomeiwen.com/subject/encgmqtx.html