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) Subject().getPrincipal();
PostVO postVO = postService.findOnePostVO(postId);
Assert.isTrue(postVO !=null,"该帖⼦已被删除");
Assert.UserId().longValue()== Id().longValue(),"没有权限操作");
model.addAttribute("post", postVO);
thymeleaf用法}
List<Category> categoryList = categoryService.findCategoryAllOfName();
model.addAttribute("list", categoryList);
return"jie/add";
}
}
前后使⽤了 th:if,th:switch,三⽬运算符等⽆法实现,⽬前来说这样可以实现
<!-- 正确写法可以实现 -->
<li class="layui-this"text="${post != null?'编辑页⾯':'添加页⾯'}"></li>
<!-- ⽆法实现 -->
<li class="layui-this"text="${post} ne 'null'?'编辑页⾯':'添加页⾯'"></li>
场景⼆
对于上述编辑页⾯,要使⽤后台数据进⾏下拉框的填充。⽽添加页⾯⽆需下拉框数据的填充。由于⼆者是公⽤⼀个页⾯,解决如下,记录⼀下
<div class="layui-input-block">
<select lay-verify="required"name="categoryId"lay-filter="column">
<option></option>
<!-- 此处遍历 -->
<option each="category:${categoryList}"value="${category.id}"
text="${category.categoryName}"
<!--加了这个‘?’⽤于判断-->
th:selected="${category.id} == ${post?.categoryId}">
</option>
</select>
</div>
th:selected="${category.id} == ${post?.categoryId}"
当在编辑页⾯时,下拉框时需要数据填充,并根据条件选中某⼀项数据
当在添加页⾯时,是不需要数据的。此时就要下拉框取消选中
这个  就是为了判断对象是否为空,如果为空就不会渲染页⾯(下拉框选中)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。