11.从零开始学springboot-整合thymeleaf

前言

上一节使用了"过时"的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

转载于:https://my.oschina.net/u/3066875/blog/3055369

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值