这篇文章主要介绍了关于thymeleaf判断对象是否为空的相关逻辑处理,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
thymeleaf 判断对象是否为空有关逻辑
场景一
在项目中,有时会遇到下面场景:
添加页面和编辑页面共用一个页面,而通过后台传来的对象来判断提示用户是编辑页面还是添加页面,而编辑页面要使用这个对象的,添加页面用不到。在此记录下自己遇到的问题,看到了别人的博客才解决了
@RequestMapping(path = {"/add", "edit"}, method = {RequestMethod.GET})
public String addOrEdit(Model model, @RequestParam(name = "postId", required = false) Long postId) {
if (!StringUtils.isEmpty(postId)) {
UserLoginResult userLoginResult = (UserLoginResult) SecurityUtils.getSubject().getPrincipal();
PostVO postVO = postService.findOnePostVO(postId);
Assert.isTrue(postVO != null, "该帖子已被删除");
Assert.isTrue(postVO.getUserId().longValue() == userLoginResult.getId().longValue(), "没有权限操作");
model.addAttribute("post", postVO);
}
List<Category> categoryList = categoryService.findCategoryAllOfName();
model.addAttribute("list", categoryList);
return "jie/add";
}
}
前后使用了 th:if,th:switch,三目运算符等无法实现,目前来说这样可以实现
<!-- 正确写法可以实现 -->
<li class="layui-this" th:text="${post != null?'编辑页面':'添加页面'}"></li>
<!-- 无法实现 -->
<li class="layui-this" th:text="${post} ne 'null'?'编辑页面':'添加页面'"></li>
场景二
对于上述编辑页面,要使用后台数据进行下拉框的填充。而添加页面无需下拉框数据的填充。由于二者是公用一个页面,解决如下,记录一下
<div class="layui-input-block">
<select lay-verify="required" name="categoryId" lay-filter="column">
<option></option>
<!-- 此处遍历 -->
<option th:each="category:${categoryList}" th:value="${category.id}"
th:text="${category.categoryName}"
<!-- 加了这个 ‘?' 用于判断 -->
th:selected="${category.id} == ${post?.categoryId}">
</option>
</select>
</div>
th:selected="${category.id} == ${post?.categoryId}"
当在编辑页面时,下拉框时需要数据填充,并根据条件选中某一项数据
当在添加页面时,是不需要数据的。此时就要下拉框取消选中
这个 ? 就是为了判断对象是否为空,如果为空就不会渲染页面(下拉框选中)
Thymeleaf基础语法
一、引用命名空间
要使用Thymeleaf,则需要先加入依赖,然后在模板文件中引用命名空间如下:
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
二、常用th标签
1. th:text
<div th:text="${name}">name</div>
它用于显示控制器传入的name值
如果name不存在,要显示默认值,则使用一下代码
<span th:text="${name}?:'默认值'"></span>
2. th:object
它用于接收后台传过来的对象,如以下代码:
<th:obejct="${user}">
3. th:action
它用来指定表单提交地址
<form th:action="@{/article}+${article.id}" method="post"></form>
4. th:value
它用对象将id的值替换为value的属性
<input type="text" th:value="${article.id}" name="id" />
5. th:field
它用来绑定后台对象和表单数据。Thymeleaf里的“th:field”等同于“th:name”和“th:value”,其具体使用方法见以下代码
<input type="text" id="title" name="title" th:field="${article.title}" />
<input type="text" id="title" name="title" th:field="*{title}" />
三、Thymeleaf中的URL写法
Thymeleaf是通过语法@{…}来处理URL的,需要使用“th:href”和“th:src”等属性,如以下代码
<a th:href="@{http://eg.com}/" rel="external nofollow" >绝对路径</a>
<a th:href="@{
本文标题为:关于thymeleaf判断对象是否为空的相关逻辑处理
- 深入了解Spring的事务传播机制 2023-06-02
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- JSP页面间传值问题实例简析 2023-08-03
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java中的日期时间处理及格式化处理 2023-04-18
- Java实现顺序表的操作详解 2023-05-19
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- JSP 制作验证码的实例详解 2023-07-30
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- Springboot整合minio实现文件服务的教程详解 2022-12-03