前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >thymeleaf使用

thymeleaf使用

作者头像
栖西
发布2023-10-17 08:21:25
1600
发布2023-10-17 08:21:25
举报
文章被收录于专栏:栖西栖西

Thymeleaf 百叶香

Thymeleaf是一个流行的模板引擎,该模板采用Java语言开发,Java生态下的模板引擎有Thymeleaf、Freemaker、Velocity、Beetl(国产)等。

代码语言:javascript
复制
Thymeleaf对网络环境要求不存在严格的要求,既能用于web环境下,也能用于非web环境下,在非web环境下
,它能直接显示模板上的静态数据,在web环境下,它能想jsp一样从后台接受数据,并替换模板上的静态数据,
是基于html的,以html标签为载体,Thymeleaf要寄托在HTML标签下实现。
springboot集成了Thymeleaf模板技术,官方推荐使用Thymeleaf来代替jsp,作为前端页面的数据展示。

在templates下的页面只能通过跳转实现(相当于WEB-INF) 静态资源放在static里面

代码语言:javascript
复制
resources
    resources
    public
    static
    templates
优先级:resources>static(默认)>public

约束 xmlns是命名空间,后面的地址是约束文件

代码语言:javascript
复制
xmlns:th="http://www.thymeleaf.org"

1、配置信息

代码语言:javascript
复制
# 设置thymeleaf模板引擎的缓存,设置为关闭,默认是true开启的
spring.thymeleaf.cache=false
# 设置thymeleaf的模板引擎的前、后缀、(可选项)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 关闭默认图标
spring.mvc.favicon.enabled=false

首页定制

代码语言:javascript
复制
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

2、基本语法

代码语言:javascript
复制
表达式
    标准表达式:${}--------th:text="${user.id}"  推荐使用
    选择表达式:*{}-------${user}---*{id}  tj:object="${user}" 不推荐使用
    路径表达式:@{}-------th:href="@{/test}"
                 --------th:href="@{/test(id=${id},age=${age})}"
                 --------th:href="@{'/test3/'+${id}+'/'+${age}}"
                 ------<img th:src="@{/img/zhien.jpeg}">
                 ------ <a th:href="@{/emp/}+${emp.getId()}">编辑</a>
                
常见属性----从后台取值的时候,使用一下,可用可不用
	th:action	定义后台控制器的路径
	th:method
	th:href
	th:src
	th:id
	th:name
	th:value
	th:attr
	th:text
	th:object
	th:onclick
	th:style
	
	th:each  可遍历:集合、map、数组
		th:each="user,userStat:${userList}"
            iterStat称作状态变量,(默认对象名加Stat)属性有:
        index:当前迭代对象的index(从0开始计算)
        count: 当前迭代对象的index(从1开始计算)
        size:被迭代对象的大小
        current:当前迭代变量
        even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
        first:布尔值,当前循环是否是第一个
        last:布尔值,当前循环是否是最后一个
        
	条件判断  th:if  th:unless  th:switch  th:case
	
	th:inline  内联表达式 [[${参数名}]] 通常写在body上,th:inline有三个取值text、javascript、none
       这个写法不推荐
        <div th:inline="text">
        数据:[[${data}]]
        </div>
        
		<script type="text/javascript" th:inline="javascript">
 		   function showData() {
     		   alert([[${data}]]);
 		   }
		</script>
		
字面量
	文本字面量
	数字字面量
	boolean字面量
	null字面量
	
字符串拼接	例如:分页  一对||内写入要拼接的字符串
<span th:text="'共'+${totalRows}+'条,'+${totalPage}+'页,'+'当前页是:'+${currentPage}">共120条12页,当前第1页,首页,上一页,下一页,尾页</span>

<p>使用更优雅的方式替拼接字符串</p>
<span th:text="|共${totalRows}条,${totalPage}页,当前第${currentPage }页,首页,上一页,下一页,尾页|">

运算符
	三元运算符:  ? :  表达式?正确结果:错误结果
    算数运算:    + - * /%
    关系比较:    > < >= <= (gr lt ge le)
    相等判断:    ==  !=  (eq  ne)

3、内置对象

代码语言:javascript
复制
功能表达式对象
内置功能对象前都需要加#号,一般以s结尾
#dates   java.util.Date对象的实用方法
		<span th:text="${#dates.format(curDate,'yyyy-MM-dd HH:mm:ss')}"></span>
#calendars  和dates类似,是 java.util.Calendar对象
#numbers    格式化数字对象的方法
#strings    字符串实用方法,contains,startsWith,prepending/appending
#objects    对objects操作的实用方法
#bools		对布尔求值的实用方法
#arrays		数组的实用方法
#lists		list的实用方法   <span th:text="${#lists.size(datas)}"></span>
#sets		set的实用方法
#map		map的实用方法
#aggregates  对数组或集合创建聚合的实用方法

内置对象
基本表达式对象
     @RequestMapping("/expression")
     public String expression(Model model, HttpServletRequest request,Integer 		id){
            model.addAttribute("username","李四");
            System.out.println(id);
            request.getSession().setAttribute("address","Session Data");
            return "index";
        }
	从session获取值:<br/>
    <span th:text="${#session.getAttribute('address')}"></span><br/>
    <span th:text="${#httpSession.getAttribute('address')}"></span><br/>
    <span th:text="${session.address}"></span><br/>
     //获取请求路径
    var requestURL = [[${#httpServletRequest.requestURL}]];  		//http://localhost:8080/expression
    var queryString =[[${#httpServletRequest.queryString}]];  //id=16

    //完整的请求路径  http://localhost:8080/expression?id=15
    var requestAddress = requestURL +"?"+queryString;

4、模板

代码语言:javascript
复制
抽取公共样式
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar"> ... </nav>
插入样式,提高代码复用性th:insert="~{页面::名字}"
<div th:insert="~{dashboard::sidebar}"> </div>
用的多的是这个:th:replace="~{commons/commons::topbar}" 替换

可以将公共的模板抽取出来
定义模板
th:fragment="head(titile)"
使用模板
th:replace="${titile}"

示例:
<head th:fragment="head(titile)">   <!-- 定义片段模板  后面的页面进行引入-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title th:replace="${titile}">博客详情</title>  <!-- 后面引用的时候进行替换  -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
</head>

引用模板
<head th:replace="_fragments :: head(~{::title})">
<title>首页</title>

自定义代码块
<th:block th:replace="script">
    <script  th:src="@{/lib/prism/prism.js}"></script>
    <script  th:src="@{/lib/tocbot/tocbot.js}"></script>
    <script  th:src="@{/lib/qrcode/qrcode.js}"></script>
</th:block>

<!-- 引用script -->  主要是/*/  /*/ 在thymeleaf模板里面是有效的
<!--/*/<th:block th:replace="_fragments :: script">/*/-->
<!--/*/</th:block>/*/-->

5、application配置文件

可能会用到的

代码语言:javascript
复制
# 服务名称
spring.application.name=eleTest

# 设置内嵌端口号
server.port=8082
server.servlet.context-path=/

# 设置thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

# 设置请求响应字符编码
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8

# 连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 数据库连接信息
spring.datasource.username=root 
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/test14?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 

# 整合Myabtis 别名 
mybatis.type-aliases-package=com.myfdc.pojo

# 前后端分离,打包后的前端文件的位置(打包后的dist文件夹下的)
spring.web.resources.static-locations=classpath:/static/

# 映射配置文件 
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

# 控制台打印SQL
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

# 展示SQL(控制台打印SQL的另一种形式)
logging.level.root=info
logging.level.com.study.dao=debug

# 设置dubbo的配置
spring.application.name=ssm-provider

# 设置当前工程为服务提供者
spring.dubbo.server=true

# 指定注册中心
spring.dubbo.regisry=zookeeper://localhost:2181

# 设置redis的配置
spring.redis.host=192.168.233.131
spring.redis.port=6379
spring.redis.password=145263

# 设置dubbo
spring.application.name=ssm-consumer
spring.dubbo.registry=zookeeper://localhost:2181

application.yml

代码语言:javascript
复制
server:
  servlet:
    context-path: /
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  port: 8088
spring:
  thymeleaf:
    cache: false

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xyxy?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456
mybatis:
  type-aliases-package: com.myfdc.domain
  mapper-locations: classpath:mapper/*.xml
  # 开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true
    # 控制台打印SQL
	log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
代码语言:javascript
复制
使用mybatis需要注意的是:
启动类上加	@MapperScan("com.myfdc.dao")
dao层加		@Repository
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-10-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、配置信息
  • 2、基本语法
  • 3、内置对象
  • 4、模板
  • 5、application配置文件
相关产品与服务
微服务引擎 TSE
微服务引擎(Tencent Cloud Service Engine)提供开箱即用的云上全场景微服务解决方案。支持开源增强的云原生注册配置中心(Zookeeper、Nacos 和 Apollo),北极星网格(腾讯自研并开源的 PolarisMesh)、云原生 API 网关(Kong)以及微服务应用托管的弹性微服务平台。微服务引擎完全兼容开源版本的使用方式,在功能、可用性和可运维性等多个方面进行增强。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档