js文件中怎么使用thymeleaf标签_SpringBoot2系列教程(七)SpringBoot整合thymeleaf

前言

早期的SpringBoot中还支持使用Velocity作为页面模板,现在的SpringBoot中已经不支持Velocity了,页面模板主要支持Thymeleaf和Freemarker,当然,作为Java最基本的页面模板Jsp也是支持的。今天,先来讲一下如何整合Thymeleaf。  

一、Thymeleaf简介

Thymeleaf是新一代Java模板引擎,支持HTML原型。由于Thymeleaf模板的后缀为.html,可以让前端工程师在浏览器中直接打开查看样式,预览的时候非常方便,也可以让后端工程师结合真实数据查看显示效果。并且SpringBoot为Thymelead提供了自动化配置解决方案,因此在SpringBoot中使用Thymeleaf非常方便。  

二、整合Thymeleaf

2.1、引入Thymeleaf依赖
   <dependency>      <groupId>org.springframework.bootgroupId>      <artifactId>spring-boot-starter-thymeleafartifactId>    dependency>    <dependency>      <groupId>org.springframework.bootgroupId>      <artifactId>spring-boot-starter-webartifactId>    dependency>
  2.2、在application.properties添加如下配置

be26ea890214450d79c92211f61e433d.png

# thymeleaf spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.check-template-location=truespring.thymeleaf.suffix=.htmlspring.thymeleaf.encoding=UTF-8spring.thymeleaf.servlet.content-type=text/html; charset=utf-8spring.thymeleaf.mode=HTML5spring.thymeleaf.cache=false
2.3、创建 Controller 注:如果不使用自定义配置也可使用SpringBoot默认的自动化配置方案,具体的配置属性在 ThymeleafProperties 这个配置类中 在controller方法中,返回视图名和数据,视图名为index则表示需要在resources/template目录下创建一个index.html的Thymeleaf文件模板。

e24451bff521409f9e220c43225cad80.png

package com.xxx.controller;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/")public class ThymeleafController {  @GetMapping("/index")  public String index(Model model) {    List users = new ArrayList<>();    for (int i = 0; i < 10; i++) {      User u = new User();      u.setId((long) i);      u.setName("小星星:" + i);      u.setAddress("厦门市:" + i);      users.add(u);    }    model.addAttribute("users", users);    model.addAttribute("userName", "小星星");    return "index";  }  public class User {    private Long id;    private String name;    private String address;    public Long getId() {      return id;    }    public void setId(Long id) {      this.id = id;    }    public String getName() {      return name;    }    public void setName(String name) {      this.name = name;    }    public String getAddress() {      return address;    }    public void setAddress(String address) {      this.address = address;    }  }}
2.4、创建 Thymeletaf 模板 在resources/template目录下创建一个index.html的Thymeleaf文件模板
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Titletitle>head><body>  <table border="1">    <tr>      <td>编号td>      <td>用户名td>      <td>地址td>    tr>    <tr th:each="user : ${users}">      <td th:text="${user.id}">td>      <td th:text="${user.name}">td>      <td th:text="${user.address}">td>    tr>  table>body>html>
2.5、验证 注:使用Thymeleaf模板引擎时,必须在html文件的html标签添加xmlns:th="http://www.thymeleaf.org,这样Thymeleaf模板才会被启用。 配置完成后,启动项目,在浏览 器输入http://127.0.0.1:8080/index 进行访问验证,出现以下页面则表示整合成功。

c86fb81f252d54846b59541a6ee30a50.png

三、基本语法

3.1、引入标签 首先要在html标签里面引入xmlns:th="http://www.thymeleaf.org"才能使用th:*这样的语法 3.2、获取变量值 通过在标签内部,使用${}来取值,对于javaBean对象,使用变量名.属性名来获取,跟EL表达式用法一样。 注:只有卸载标签内部才会生效,例如

xxx

的意思是使用hello来代替p之前的内容,实际显示在页面上的数据是hello 3.3、引入URL Thymelead引入url采用@{...}来获取,例如, 3.4、字符串替换 或者都可以实现替换。 注:|...|中只能包含变量表达式${...},不能包含其他常量、条件表达式等。 3.5、运算符 在表达式中可以使用各类算数运算符+,-,*,/,%,例如th:with="isEven(=${count}%2==0)",逻辑运算符>,=,==,!=都可以使用,唯一需要注意的是使用时需要用它的HTML转义字符3.6、条件th:if是该标签在满足条件的时候才会显示,th:unless是不成立的时候才显示:LoginThymeleaf同时支持使用switch结构判断,默认属性(default)用*表示,例如:
<div th:switch="${user.role}">  <p th:case="'admin'">User is an administratorp>  <p th:case="#{roles.manager}">User is a managerp>  <p th:case="*">User is some other thingp>div>
3.7、循环   Th:each是对结构进行遍历的数据集,例如:
<tr th:each="user : ${users}">  <td th:text="${user.id}">td>  <td th:text="${user.name}">td>  <td th:text="${user.address}">td>tr>

四、常用标签 

  • th:text:替换原来text中的东西

  • th:value:替换原来value的值

  • th:object:替换标签的对象,th:object=“对象”

  • th:field:填充,如图上面有对象,可以直接用*{属性}取值

  • th:checked:当check的值为true时候为选中,false时为未选中

  • th:remove:删除

  • th:href:用@{}替换连接地址

  • th:if:如果值为true的时候才显示标签,否则不显示

  • th:unless:不成立的时候才显示

  • th:each:用户循环遍历结果集

  • th:style:替换样式

  • th:action:替换action地址,用@{}取地址

  • th:alt:用@{}取地址

  • th:class:替换class的样式

  • th:fragment:定义一个framemet模板,在后面引用他

关于本文,如有问题,欢迎留言讨论。 本公众号会不定时给小伙伴们带来java实用技术分享,喜欢的小伙伴欢迎关注小星的公众号。

cee7c1952b9b5d1d24f7006ef11d725c.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你在使用 Thymeleaf 时遇到了页面报错,可以查看控制台输出的错误信息,找到具体的问题所在。常见的错误包括语法错误、模板引用错误、标签使用错误等等。 如果你想利用 Thymeleaf 自定义错误页面,可以按照以下步骤进行: 1. 首先在 `src/main/resources/templates` 目录下创建一个 `error` 目录。在该目录下创建一个名为 `error.html` 的 Thymeleaf 模板文件。 2. 在 `application.properties` 文件配置错误处理的地址: ``` server.error.path=/error ``` 3. 创建一个名为 `ErrorController` 的控制器类,用于处理错误请求: ```java @Controller public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController { @RequestMapping("/error") public String handleError(HttpServletRequest request, HttpServletResponse response) { // 获取错误状态码 Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); // 根据状态码返回不同的错误页面 if (statusCode == 404) { return "error/404"; } else { return "error/500"; } } @Override public String getErrorPath() { return "/error"; } } ``` 4. 在 `error` 目录下创建 `404.html` 和 `500.html` 两个 Thymeleaf 模板文件,用于显示不同类型的错误页面。 例如,`404.html` 可以这样编写: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>404 Not Found</title> </head> <body> <h1>404 Not Found</h1> <p>您请求的页面不存在,请检查您输入的地址是否正确。</p> </body> </html> ``` 5. 访问不存在的页面,尝试触发 404 错误,可以看到自定义的错误页面。 如果你想测试 500 错误,可以在控制器抛出一个异常,例如: ```java @RequestMapping("/test") public String test() { throw new RuntimeException("测试错误"); } ``` 然后访问 `/test` 地址即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值