当前位置: 首页 > news >正文

网站服务器++免费做电子手抄报的网站

网站服务器++免费,做电子手抄报的网站,杭州营销策划推广公司,项目四网站建设实训报告引言:为什么选择 Thymeleaf? Thymeleaf 是一个现代化的服务器端 Java 模板引擎,专为 Web 开发而设计。与 JSP 不同,Thymeleaf 模板是纯 HTML 文件,可以直接在浏览器中预览,无需后端服务器支持。这种"…

引言:为什么选择 Thymeleaf?

Thymeleaf 是一个现代化的服务器端 Java 模板引擎,专为 Web 开发而设计。与 JSP 不同,Thymeleaf 模板是纯 HTML 文件,可以直接在浏览器中预览,无需后端服务器支持。这种"自然模板"特性让前端开发和后端开发可以无缝协作。Spring Boot 官方推荐使用 Thymeleaf 作为视图技术,它提供了:

  • 简洁优雅的语法

  • 强大的表达式语言

  • 与 Spring 生态的完美集成

  • 丰富的布局功能

  • 开箱即用的国际化支持

本文将带你从零开始,全面掌握 Spring Boot 中 Thymeleaf 的使用。

一、环境搭建

1. 创建 Spring Boot 项目

使用 Spring Initializr (https://start.spring.io/) 创建项目,选择以下依赖:

  • Spring Web

  • Thymeleaf

2. Maven 依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
</dependencies>

3. 目录结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── controller
│   │               ├── model
│   │               └── DemoApplication.java
│   └── resources
│       ├── static   # 静态资源(CSS, JS, 图片)
│       ├── templates # Thymeleaf 模板
│       └── application.properties

二、基础配置

application.properties 配置

# Thymeleaf 配置
spring.thymeleaf.cache=false # 开发时关闭缓存
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8# 静态资源路径
spring.resources.static-locations=classpath:/static/

三、第一个 Thymeleaf 页面

1. 创建控制器

@Controller
public class HomeController {@GetMapping("/")public String home(Model model) {model.addAttribute("message", "Hello, Thymeleaf!");model.addAttribute("currentDate", new Date());return "home"; // 对应 templates/home.html}
}

2. 创建模板文件 (templates/home.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Thymeleaf 入门</title>
</head>
<body><h1 th:text="${message}">默认标题</h1><p>当前时间:<span th:text="${#dates.format(currentDate, 'yyyy-MM-dd HH:mm:ss')}"></span></p><!-- 使用 Thymeleaf 表达式 --><div th:if="${not #strings.isEmpty(message)}"><p>消息长度:<span th:text="${#strings.length(message)}"></span></p></div><!-- 链接表达式 --><a th:href="@{/about}">关于我们</a>
</body>
</html>

3. 运行并访问

启动应用后访问 http://localhost:8080,你将看到:

  1. "Hello, Thymeleaf!" 标题

  2. 格式化的当前时间

  3. 消息长度计算

  4. 指向关于页面的链接

四、Thymeleaf 核心语法

1. 变量表达式 (${...})

用于访问模型中的数据:

<p th:text="${user.name}">用户名</p>
<p th:text="${user.age > 18 ? '成年' : '未成年'}">年龄状态</p>

2. 选择表达式 (*{...})

与 th:object 配合使用:

<div th:object="${user}"><p>姓名: <span th:text="*{name}"></span></p><p>邮箱: <span th:text="*{email}"></span></p>
</div>

3. 消息表达式 (#{...})

用于国际化:

<p th:text="#{welcome.message}">欢迎信息</p>

4. 链接表达式 (@{...})

生成正确的 URL:

<a th:href="@{/users/{id}/profile(id=${userId})}">用户资料</a>
<img th:src="@{/images/logo.png}">

5. 片段表达式 (~{...})

包含模板片段:

<div th:insert="~{fragments/header :: header}"></div>

五、常用功能详解

1. 条件判断

<div th:if="${user.isAdmin}"><button>管理面板</button>
</div><div th:unless="${user.active}"><p class="warning">账户未激活</p>
</div><div th:switch="${user.role}"><p th:case="'admin'">管理员</p><p th:case="'user'">普通用户</p><p th:case="*">未知角色</p>
</div>

2. 循环遍历

<table><tr th:each="user, iterStat : ${users}"><td th:text="${iterStat.index + 1}">序号</td><td th:text="${user.name}">姓名</td><td th:text="${user.email}">邮箱</td><td><span th:if="${user.active}" th:text="激活"></span><span th:unless="${user.active}" th:text="未激活"></span></td></tr>
</table>

3. 表单处理

<form th:action="@{/users}" th:object="${user}" method="post"><input type="text" th:field="*{name}" placeholder="姓名"><input type="email" th:field="*{email}" placeholder="邮箱"><button type="submit">保存</button><!-- 显示字段错误 --><div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="error"></div>
</form>

4. 布局模板

layout.html (布局文件)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title th:text="${title}">默认标题</title><th:block th:replace="fragments/head :: head"></th:block>
</head>
<body><header th:replace="fragments/header :: header"></header><main><!-- 内容区域 --><div th:replace="${view}"></div></main><footer th:replace="fragments/footer :: footer"></footer>
</body>
</html>

home.html (具体页面)

<!DOCTYPE html>
<html th:replace="~{layout :: layout(~{::title}, ~{::main})}">
<head><title>首页</title>
</head>
<body><main><h1>欢迎来到首页</h1><p>这是主要内容区域</p></main>
</body>
</html>

六、实用技巧与最佳实践

1. 工具对象

Thymeleaf 提供了一系列实用工具:

  • #dates:日期格式化

  • #strings:字符串操作

  • #numbers:数字格式化

  • #lists:集合操作

  • #arrays:数组操作

  • #objects:对象操作

    <p th:text="${#dates.format(user.birthday, 'yyyy年MM月dd日')}"></p>
    <p th:text="${#strings.capitalize(user.name)}"></p>
    <p th:text="${#lists.size(user.roles)}"></p>

2. 内联表达式

使用 [[...]] 或 [(...)] 在 HTML 属性中内联表达式:

<script th:inline="javascript">var userId = [[${user.id}]];var userName = /*[[${user.name}]]*/ '默认名称';
</script><p data-user-id="${user.id}">用户ID: [[${user.id}]]</p>

3. 模板缓存管理

开发环境关闭缓存,生产环境开启缓存:

# application-dev.properties
spring.thymeleaf.cache=false# application-prod.properties
spring.thymeleaf.cache=true

4. 自定义方言

创建自定义 Thymeleaf 处理器:

public class AlertDialect extends AbstractProcessorDialect {public AlertDialect() {super("Alert Dialect", "alert", 1000);}@Overridepublic Set<IProcessor> getProcessors(String dialectPrefix) {return Set.of(new AlertTagProcessor(dialectPrefix));}
}public class AlertTagProcessor extends AbstractElementTagProcessor {// 实现自定义标签处理逻辑
}

注册方言:

@Configuration
public class ThymeleafConfig {@Beanpublic AlertDialect alertDialect() {return new AlertDialect();}
}

七、常见问题解决

1. 静态资源加载问题

确保路径正确:

<!-- 正确方式 -->
<link th:href="@{/css/style.css}" rel="stylesheet"><!-- 错误方式 -->
<link href="/css/style.css" rel="stylesheet">

2. 表单绑定失败

确保表单对象和字段名匹配:

// Controller
@PostMapping("/save")
public String saveUser(@ModelAttribute("userForm") User user) {// ...
}
<!-- 模板 -->
<form th:object="${userForm}"><input th:field="*{name}">
</form>

3. 国际化支持

配置消息源:

# application.properties
spring.messages.basename=messages

创建 messages.properties:

welcome.message=欢迎您, {0}!

在模板中使用:

<p th:text="#{welcome.message(${user.name})}"></p>

八、进阶学习资源

  1. 官方文档

    • Thymeleaf 官方文档

    • Spring Boot Thymeleaf 文档

  2. 推荐书籍

    • "Thymeleaf: Practical Natural Templates" by José Samper

    • "Spring Boot in Action" by Craig Walls

  3. 实战项目

    • GitHub 搜索 "spring-boot-thymeleaf-example"

    • Spring 官方示例项目

总结

Thymeleaf 作为 Spring Boot 的官方推荐模板引擎,提供了强大的功能和优雅的语法。通过本文的学习,你应该能够:

  1. 搭建 Spring Boot + Thymeleaf 开发环境

  2. 使用基础表达式和常用功能

  3. 实现复杂的页面布局

  4. 处理表单和验证

  5. 解决常见开发问题

Thymeleaf 的"自然模板"特性使其成为现代 Web 开发的理想选择,它让前后端协作更加高效。现在就开始在你的项目中尝试使用 Thymeleaf 吧!

http://www.dtcms.com/a/553418.html

相关文章:

  • 单页网站的优点网络公司是做什么的?
  • 阿瓦隆 Q 90T矿机:低功耗高效挖矿,是否值得选择?
  • 印度实时股票数据源接口对接文档-IPO新股、k线数据
  • HTTPS接口国密安全设计(含防重放设计)
  • 网站设计公司(信科网络)中国制造网外贸平台怎么注册
  • 网站模版如何去除title版权信息499元做网站
  • 武进建设局网站首页胖鼠wordpress
  • 机器学习第一阶段
  • Linux内核RDMA用户态内存映射机制深度解析:零拷贝高性能的基石
  • 组态软件和实时数据库区别大吗?
  • SpringBoot】Spring Boot 项目的打包配置
  • 递归专题5 - FloodFill算法专题
  • 系统架构设计师论文-论软件架构的复用
  • 沙市做网站weiswordwordpress微信登录设置
  • 理解MySQL的原理
  • Mac通过命令行开启ssh服务
  • 哈尔滨有哪些做网站的公司站长工具seo综合查询问题
  • 珠海做网站的wordpress 写作
  • 【计算机基础】之核心架构
  • 临西网站建设公司公司核名查询官网
  • PPIO独家上新GPU实例模板,一键部署Kimi-Linear
  • 工业级电池健康管理利器:GRX-3000 系列电池诊断站技术解析
  • 旅游网站建设功能意义wordpress 模板 免费
  • 周口市住房和城市建设局网站自做网站打开速度慢
  • STM32H743-ARM例程35-DHCP
  • 概率论直觉(一):大数定律
  • 数据结构—栈和队列
  • JavaSE知识分享——继承(下)
  • Linux性能分析:常用工具与指令
  • 软件测试面试的排序算法问题如何回答