栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringBoot之使用Thymeleaf视图模板

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot之使用Thymeleaf视图模板

前言

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

一、目标

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

二、实现

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

 
        
            org.springframework.boot
            spring-boot-starter
        

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

添加完依赖以后,就需要编写对应的Controller跟view了

在resource目录下新建templates文件夹并且在该目录下新建文件index.html


    
    Title
    你好
      

在src/main/java/com/yukong/chapter目录下新建IndexController

@Controllerpublic 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相关配置

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



作者:余空啊
链接:https://www.jianshu.com/p/66d1be96ea1e


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235668.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号