Springboot中thymeleaf

博客指出Spring Boot中不推荐使用JSP,推荐使用模板,着重介绍了Thymeleaf。包括添加依赖、在配置文件中进行配置、创建HTML文件和控制器等步骤,还详细介绍了Thymeleaf的语法,如引用命名空间、输出内容、访问对象、基本语法等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       由于使用JSP页面时,编译器会把JSP页面编译成serverlet,这样比较消耗资源,所以在springBoot中不推荐使用JSP,推荐大家使用模板,Thymleaf、Freemaker、Grooay,在这里来介绍一下Thymleaf

1、添加依赖

  1. <!--html 解析引擎 -->
  2. <dependency>
  3.    <groupId>org.springframework.boot</groupId>
  4.    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  5. </dependency>

    注:可以在配置文件中添加Theymleaf的版本,为了是日志文件中不在记录Themleaf日志

  1. <properties>
  2.           <!-- 不再显示thymeleaf的日志 -->
  3.        <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
  4.        <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
  5. </properties>

2、在aplication.properties中进行Themleaf配置

  1. #不使用缓存
  2. spring.thymeleaf.cache=false    #html具有缓存的特点,这里不用,每次刷新都请求服务器
  3. spring.thymeleaf.prefix=classpath:/templates/
  4. spring.thymeleaf.suffix=.html
  5. spring.thymeleaf.mode=HTML5
  6. spring.thymeleaf.encoding=UTF-8

3、在resources问价夹下建立templates文件夹,放置html文件

以base.html为例

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
  3.       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
  4. <head>
  5.     <title>基础数据上传页面</title>
  6. </head>
  7. <body>
  8. <center><h2 th:inline="text">这是基础数据的上传页面</h2>
  9. <p th:text="${name}"></p>
  10. <form action="/upload/basic" method="POST" enctype="multipart/form-data">
  11.     <div>选择要上传的文件,必须是Excel2007以上的版本(以.xlsx结尾)</div><br/>
  12.     <input  type="file"  name="file"/>
  13.     <br/>
  14.     <button style="color: red">提交了</button>
  15. </form>
  16. </center>
  17. </body>
  18. </html>

4、创建controller控制器进行页面跳转

  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import java.util.Map;
  4. /**
  5.  * @author Baron
  6.  * @Description: test
  7.  * @date 2019-07-11 08:17
  8.  */
  9. @Controller
  10. public class DemoController {
  11.     /**
  12.      * 跳转到基础数据上传的页面
  13.      */
  14.     @GetMapping("to_basic")
  15.     public String jumpToBasic(Map<String, Object> map) {
  16.         map.put("name", "测试 thymleaf");
  17.         return "/basic";
  18.     }
  19. }

前段取出name值加载到页面

下面介绍一下thymeleaf的语法,其实没啥的,不知道怎么实现,看看就行了:

一、引用命名空间 <html xmlns:th="http://www.thymeleaf.org"> 

        在html中引入此命名空间,可避免编辑器出现html验证错误,虽然加不加命名空间对Thymeleaf的功能没有任何影响。

 

二、输出内容

        2.1  <p th:text="#{home.welcome}">Welcome to our grocery store!</p>

        说明:

                 1. th:text  用来将内容输出到所在标签的body中。

                 2. #{home.welcome} 用来引入数据home对象中的 welcome属性。

                 3. 可以用th:utext 用来显示“unescaped ” 的html内容。

        2.2    <p>Today is: <span th:text="${today}">13 February 2011</span></p>

        说明:${today} 用来引用 today 变量

三、访问对象      

       ${param.x} 返回名为x 的 request参数。(可能有多个值)

       ${session.x} 返回名为x的Session参数。

       ${application.x} 返回名为 servlet context 的参数。

     

四、基本语法

       4.1  #{home.welcome} --  访问数据

       4.2  #{home.welcome(${session.user.name})}  -- 格式化数据 当 home.welcome 为 "abcdegf{0}"  类似这种内容时。(多个参数以逗句分隔)。

       4.3  ${today} --- 访问变量

       4.4  访问基本对象

#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.

其它公共对象参考: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

        4.5  日期的输出

        <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>

        4.6  星号语法

<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

4.7  输出URL

       <a href="product/list.html" th:href="@{/product/list}">Product List</a>

       <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

       4.8  使用代码段

       <div th:insert="~{commons :: main}">...</div>

       4.9  直接输出内容   

<span th:text="'working web application'"> -- 输出字符

<span th:text="2013 + 2">  -- 输出数据表达式

<div th:if="${user.isAdmin()} == false">  --输出布尔表达式

<span th:text="'Welcome to our application, ' + ${user.name} + '!'"> -- 带变量的

4.10 条件表达式

<tr th:class="${row.even}? 'even' : 'odd'">
...  
</tr>

<tr th:class="${row.even}? 'alt'">
...省略 false 结果的表达方式
</tr>

<div th:object="${session.user}">
...省略 true 结果的表达方式
<p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
</div>

<span th:text="${user.name} ?: _">no user authenticated</span> --不做任何处理时用下划线 _ 表示

4.11  格式化 

       <td th:text="${{user.lastAccessDate}}">...</td> --${{.}}  调用默认的格式化器来输出结果。

       4.12  预处理

       <p th:text="${__#{article.text('textVar')}__}">Some text here...</p>  

       说明:thymeleaf 的处理模板内容的顺序与书写顺序无关,只能通过  __${expression}__ ,来将需要先一步计算出来后面          要用的变量指定为优化处理。

 

 五、设置 Attribute 值

       5.1 设置任何Attribute 的方法

       <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>   --设置单个

       <img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />  --一次设置多个

        5.2 设置一些内置的Attribute的方法   

       <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

       <form action="subscribe.html" th:action="@{/subscribe}">

       <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

       <img src="../../images/gtvglogo.png"  th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" /> -- 一次设置多个(alt title)的方法

       其它的可用属性:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes

        5.3 设置html里没有指的任何属性的语法

        <span th:whatever="${user.name}">...</span>   ---whatever 可以换成任何你想设的属性

 

六、循环输出的语法

       6.1 基本循环

<tr th:each="prod : ${prods}">

     <td th:text="${prod.name}">Onions</td>
     <td th:text="${prod.price}">2.41</td>
     <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

6.2 循环状态的使用

<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>

       关于状态的其它信息的使用详细参考:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#keeping-iteration-status

       

七、条件判断

       7.1 if 和 unless

       <a href="comments.html" th:href="@{/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a>

       <a href="comments.html"  th:href="@{/product/comments(prodId=${prod.id})}"   th:if="${not #lists.isEmpty(prod.comments)}">view</a>

       7.2 switch 语句

<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>    --默认的 case 相当于default
</div>

 

八、模板 include

      8.1 定义和引用代码块

      定义代码块

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<body>
      <div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
     </div>
    </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值