Thymeleaf公共代码抽取

博客围绕Spring Boot展开,介绍了公共代码的相关内容,包括引入公共代码的方法,还提及了处理高亮的操作,最后展示了相应效果,涉及Thymeleaf等技术。

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

  1. 1公共代码

  1. 2引入公共代码

  1. 3处理高亮

  1. 4效果

 

 

### Thymeleaf前端代码示例 #### HTML页面中的Thymeleaf语法应用 在HTML文件中,`<div>`或其他标签内可以嵌入Thymeleaf表达式来动态渲染内容: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>用户信息</title> </head> <body> <h1 th:text="'欢迎, ' + ${user.name}"></h1> <p th:if="${user.isAdmin()}">管理员专有内容</p> <ul> <!-- 使用迭代器遍历列表 --> <li th:each="item : ${items}" th:text="${item.description}"> 商品描述会在这里显示 </li> </ul> <!-- 表单提交 --> <form action="#" th:action="@{/submitForm}" method="post"> 用户名:<input type="text" name="username"/> 密码:<input type="password" name="password"/> <button type="submit">登录</button> </form> </body> </html> ``` 此段代码展示了如何利用Thymeleaf的条件判断语句、循环结构以及表单处理功能[^1]。 #### 集成Spring Boot后的控制器层交互 当与Spring框架一起工作时,在控制器方法返回视图名称之前,先向模型(Model)添加所需的数据。这样可以在视图解析期间访问这些变量并将其注入到模板中[^3]。 ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class UserController { @GetMapping("/profile") public String userProfile(Model model){ User user = new User(); user.setName("张三"); user.setAdmin(true); List<Item> items = Arrays.asList( new Item("苹果", 5), new Item("香蕉", 7) ); model.addAttribute("user", user); model.addAttribute("items", items); return "userProfile"; // 对应于/userProfile.html路径下的模板文件 } } ``` 上述Java代码片段说明了怎样在一个简单的GET请求处理器里准备要传送给前端的信息,并指定哪个Thymeleaf模板应该被用来呈现响应结果。 #### 关键特性支持 除了基本的功能外,Thymeleaf还提供了强大的内置工具集,比如自然模板模式(Natural Templates),这意味着即使不经过服务器端渲染也能正常查看网页布局;还有丰富的URL链接构建方式(@{})等实用特性[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值