问题:
我在Spring MVC中有一个Thymeleaf模板,我想用它做两件事:
1)对于在数据库中创建新实体
2)对于更新数据库中的现有实体
这两个用例之间只有一个微小的区别:数据库中的实体有一个版本(乐观锁定)属性集,所以我想记住这个版本作为隐藏字段模板,这很容易做到。
为了更好地了解我来自这里的是创建新实体的处理程序代码:
@GetMapping("/new")
String showMapFormForAdd( Model model ) {
model.addAttribute( "map", null ); // PASS null into it
return "map-form"; // same template
}
以下是更新现有实体的代码:
@GetMapping("/{mapId}/update")
public String showMapFormForUpdate( @PathVariable Long mapId, Model model ) {
GameMap map = mapService.findMap( mapId );
model.addAttribute( "map", map ); // PASS the real map into it (with version!!!)
return "map-form"; // same template
}
以下是Thymeleaf 模板中隐藏版本字段的代码:
<input type="hidden" th:value="${map?.version}" name="version" />
但是,当模板在第一个处理程序(创建)之后呈现时,我得到一个异常,即属性版本不存在(它的真实,它不存在)。
问题:
我如何告诉Thymeleaf,只有在注入Thymeleaf的“map”模型中存在属性version
时才查询版本并将其设置为隐藏字段中的值?
答案 0 :(得分:1)
您可以添加条件th:值
<input type="hidden" th:value="${map.version != null ? map.version : ''}" name="version" />