springboot整合thymeleaf模板引擎

1.什么是thyeleaf模板引擎

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。

是新一代 Java 模板引擎,它支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

作用:

将模板(页面)和数据进行整合然后输出显示

2.使用

在创建好的Springboot项目中的pom文件添加thymeleaf依赖

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

在application.properties或者application.yml里配置相关内容

#开发时关闭缓存,不然没法看到实时页面
	spring.thymeleaf.cache=false
	spring.thymeleaf.mode=HTML5
	#前缀
	spring.thymeleaf.prefix=classpath:/templates/
	#编码
	spring.thymeleaf.encoding=UTF-8
	#类型
	spring.thymeleaf.content-type=text/html
	#名称的后缀
	spring.thymeleaf.suffix=.html

示例: 

1.创建好实体类(User)

package com.example.model;

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private  String pwd;

}

2.在controller包下创建ThymeleafController类

package com.example.controller;

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


@Controller
@RequestMapping("tpl")
public class ThymeleafController {
    @GetMapping("thymeleaf")
    public String index(Model model){
        model.addAttribute("id","123");
        model.addAttribute("name","张三");
        model.addAttribute("pwd","abc");
        return "thymeleaf/index";
    }
}

3.在templates目录下创建index.html文件

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>SpringBoot模版渲染</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="'用户ID:' + ${id}"/>
<p th:text="'用户名称:' + ${name}"/>
<p th:text="'用户密码:' + ${pwd}"/>
</body>
</html>

<html xmlns:th="http://www.thymeleaf.org">  这一条语句是必不可少 

 然后启动项目

项目启动成功

获取访问url

 

会生成如上访问地址,然后去浏览器里访问

最后:

 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值