• springboot整合thymeleaf模板引擎


    1.什么是thyeleaf模板引擎

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

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

    作用:

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

    2.使用

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


        org.springframework.boot
        spring-boot-starter-thymeleaf

     

    在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)

    1. package com.example.model;
    2. import lombok.Data;
    3. @Data
    4. public class User {
    5. private int id;
    6. private String name;
    7. private String pwd;
    8. }

    2.在controller包下创建ThymeleafController类

    1. package com.example.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.ui.Model;
    4. import org.springframework.web.bind.annotation.GetMapping;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. @Controller
    7. @RequestMapping("tpl")
    8. public class ThymeleafController {
    9. @GetMapping("thymeleaf")
    10. public String index(Model model){
    11. model.addAttribute("id","123");
    12. model.addAttribute("name","张三");
    13. model.addAttribute("pwd","abc");
    14. return "thymeleaf/index";
    15. }
    16. }

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

    1. "http://www.thymeleaf.org">
    2. SpringBoot模版渲染
    3. "Content-Type" content="text/html;charset=UTF-8"/>
    4. "'用户ID:' + ${id}"/>

    5. "'用户名称:' + ${name}"/>

    6. "'用户密码:' + ${pwd}"/>

      这一条语句是必不可少 

     然后启动项目

    项目启动成功

    获取访问url

     

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

    最后:

     


     

  • 相关阅读:
    原子搜索算法改进的深度极限学习机DELM的分类
    gbk与utf8自动识别
    HTML+CSS简单的网页制作期末作业——浙江旅游景点介绍网页制作
    【技术分享】万字长文图文并茂读懂高性能无锁 “B-Tree 改”:Bw-Tree
    typescript学习笔记
    MySQL事务(Transaction)
    Git版本控制:入门到精通
    马踏棋盘算法 贪心算法优化
    [深入研究4G/5G/6G专题-45]: L3信令控制-1-软件功能和整体架构
    【RPG Maker MV 仿新仙剑 战斗场景UI (三)】
  • 原文地址:https://blog.csdn.net/m0_67930426/article/details/133689192