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}"

    当在编辑页面时,下拉框时需要数据填充,并根据条件选中某一项数据 当在添加页面时,是不需要数据的。此时就要下拉框取消选中 这个 ? 就是为了判断对象是否为空,如果为空就不会渲染页面(下拉框选中)
经验分享 程序员 微信小程序 职场和发展