SpringBoot中使用Thymeleaf模板详情

网友投稿 658 2022-10-10

SpringBoot中使用Thymeleaf模板详情

SpringBoot中使用Thymeleaf模板详情

目录一.什么是Thymeleaf二.SpringBoot中使用Thymeleaf模板1.pom.xml中添加thymeleaf依赖2.关闭thymeleaf缓存3.创建thymeleaf模板页面4.创建一个类(用于与上述html页面交互)5.访问服务路径

一.什么是Thymeleaf

官网原话:Thymeleaf是适用于Web和独立环境的现代服务器端java模板引擎,能够处理HTML,XML,javascript,css甚至纯文本。 Thymeleaf的主要目标是提供一种优雅且高度可维护的模板创建方式。为此,它以自然模板的概念为基础,以不影响模板用作设计原型的方式将其逻辑注入模板文件。这样可以改善设计沟通,并缩小设计团队与开发团队之间的差距。Thymeleaf是一个HTML5模板引擎,可用于Web环境中的应用开发。Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替jsP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式。thymeleaf模板引擎,替代jsp。

二.SpringBoot中使用Thymeleaf模板

1.pom.xml中添加thymeleaf依赖

org.springframework.boot

spring-boot-starter-thymeleaf

2.关闭thymeleaf缓存

在application.yml中的spring:下添加如下代码(能让改动的页面及时生效,实现类似热部署效果):

#能让改动的页面及时生效,实现类似热部署效果

thymeleaf:

cache: false

注意缩进,添加后缩进如下:

3.创建thymeleaf模板页面

创建一个普通的html文件hello.html,如下:

在html的标签上加入名称空间xmlns:th="http://thymeleaf.org"表示该页面是一个thymeleaf模板页面。 即把上述代码中换成 这样就可以在页面中的标签内使用th属性取出model中的值,类似于EL表达式。 具体用法http://代码如下:

欢迎来到中国,我叫,今年岁。

4.创建一个类(用于与上述html页面交互)

ackage com.ysw.springboot01.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller

@RequestMapping("/thy")

public class ThymeleafController {

@RequestMapping("/hello")

public String hello0(Model model){

//向model中存入数据

model.addAttribute("nahttp://me","李白");

model.addAttribute("age","18");

//跳转到hello.html模版引擎

return "hello";

}

}

5.访问服务路径

效果如下:

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【JiuDu OJ 04】what day is Date?
下一篇:【九度 OJ 05】统计同成绩学生人数
相关文章

 发表评论

暂时没有评论,来抢沙发吧~