如何在SpringBoot中引入Thymeleaf-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

如何在SpringBoot中引入Thymeleaf

如何在SpringBoot中引入Thymeleaf?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

成都创新互联公司是创新、创意、研发型一体的综合型网站建设公司,自成立以来公司不断探索创新,始终坚持为客户提供满意周到的服务,在本地打下了良好的口碑,在过去的10余年时间我们累计服务了上千家以及全国政企客户,如小搅拌车等企业单位,完善的项目管理流程,严格把控项目进度与质量监控加上过硬的技术实力获得客户的一致赞扬。

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

1.Thymeleaf简介

Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用 

Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模,Thymeleaf的可扩展性也非常棒。你可以使用它定义自己的模板属性集合,这样就可以计算自定义表达式并使用自定义逻辑,Thymeleaf还可以作为模板引擎框架。

2.引入Thymeleaf

引入依赖

在maven(pom.xml)中直接引入:


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


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

配置Thymeleaf

在application.yml配置Thymeleaf

server:
 port: 8000
spring:
 thymeleaf:
 cache: false # 关闭页面缓存
 encoding: UTF-8 # 模板编码
 prefix: classpath:/templates/ # 页面映射路径
 suffix: .html # 试图后的后缀
 mode: HTML5 # 模板模式

# 其他具体配置可参考org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
# 上面的配置实际上就是注入该类的属性值

demo示例

创建IndexController

@Controller
public class IndexController {
 // 返回视图页面
 @RequestMapping("index")
 public String index(){
  return "index";
 }

}

创建index.html




 
 Title


 Hello Thymeleaf!

创建TestController

@RestController
public class TestController {
 
 // 返回整个页面
 @RequestMapping("/test")
 public ModelAndView test(){
  return new ModelAndView("test");
 }
}

创建test.html




 
 Title


Hello Thymeleaf! 
By: ModelAndView

3.测试结果

如何在SpringBoot中引入Thymeleaf
如何在SpringBoot中引入Thymeleaf

4.Thymeleaf基础语法及使用

1.引入标签 

html标签里引入xmlns:th="http://www.thymeleaf.org"才能使用th:*这样的语法

2.引入URL 

@{...} 

例如:

绝对路径 是访问绝对路径下的URL, 相对路径 是访问相对路径下的URL。

是引入默认的static下的css文件夹下的bootstrap文件,类似的标签有: th:href 和 th:src

3.获取变量 

通过${}取值,对于JavaBean的话,使用变量名.属性名获取

4.字符串替换


或者

注意:|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等

5.运算符 

   在表达式中可以使用各类算术运算符
   例如 (+, -, *, /, %)
   例如:th:with="isEven=(${stat.number} % 1 == 0)"
   逻辑运算符 (>, <, <=,>=,==,!=)
   需要注意的是使用<,>的时候需要转义

th:if="${stat.number} > 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

6.条件 

if/unless th:if是该标签在满足条件的时候才会显示,unless是不成立时候才显示

Login

switch  thymeleaf支持switch结构,默认属性(default)用*表示


  User is an administrator

  User is a manager

  User is some other thing

7.循环


 Onions
 2.41
 yes

8.Utilities

内置在Context中,可以直接通过#访问
#dates
#calendars
#numbers
#strings
arrays
lists
sets
maps

关于如何在SpringBoot中引入Thymeleaf问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


当前名称:如何在SpringBoot中引入Thymeleaf
URL地址:http://kswsj.cn/article/ggpeso.html

其他资讯