在Thymeleaf模板中显示Springboot验证结果



我刚开始使用Springboot,但无法将验证结果(错误)传播回百里香模板。我有一个典型的设置:@Entity对象、@Service和@Repository。以下是我的控制器和索引模板(及其表单)的部分。UserVital、UserBlood等是使用hibernate映射到DB表的数据对象。希望这些信息足以让会员们为我指明正确的方向。

<<p>数据对象/strong>
@Entity
@Table(name = ".....")
public class UserVital {
@NotNull(message = "Height (Feet) cannot be null")
@Range(min = 0, max = 15, message = "Height (Feet) must be greater than 0")
@Column(name = "feet", nullable = false)
private int heightInFeet;
.............
}

控制器

@GetMapping("/")
public String getUsers(Model model) {
UserVital vital = new UserVital();
UserGrithMeasurements grith = new UserGrithMeasurements();
UserBloodChemistry blood = new UserBloodChemistry();
List<Category> categories = categoryService.getAllCategories();
model.addAttribute("categories", categories.get(0));
model.addAttribute("vital", vital);
model.addAttribute("grith", grith);
model.addAttribute("blood", blood);
return "index";
}
@PostMapping("/add")
public String addData(@Valid UserVital vital, BindingResult vitalValidationResult,
@Valid UserGrithMeasurements grith, BindingResult grithValidationResult, @Valid UserBloodChemistry blood,
BindingResult bloodValidationResult, Model model) {
if (vitalValidationResult.hasErrors() || grithValidationResult.hasErrors()
|| bloodValidationResult.hasErrors()) {
return "index";
} else {
model.addAttribute("successMsg", "Details saved successfully!!");
return "index";
}
}
<<p>百里香形式/strong>
<form class="tab-content" method="POST" th:action="@{/add}">
<div class="form-group row">
<label for="height" class="col-sm-2 control-label" th:text="#{height}"></label>
<div class="col-sm-2">
<input type="number" class="form-control" id="feet" th:attr="placeholder=#{feet}"
th:field="${vital.heightInFeet}">
</div>
<div class="form-group col-sm-12">
<label for="neck" class="col-sm-2 control-label" th:text="#{neck}"></label>
<div class="col-sm-2">
<input type="number" class="form-control" id="systolic" th:attr="placeholder=#{inches}"
th:field="${grith.neck}">
<div class="col-sm-2">
<input type="number" class="form-control" id="ldl" th:field="${blood.ldl}">
.....
</form>

如你所见,我有多个BindingResult对象。每个BindingResult对象保存各自数据对象的验证结果(vitalValidationResult保存UserVital对象vital的验证结果,等等)。现在,我怎么写"if"呢?模板中的语句将允许我检查字段中是否有任何错误。

谢谢。

通过将所需的表单字段封装在div中,然后放置"th:object=${objectName}">

<form >
<div class="tab-pane active text-center" id="tab_1_1" th:object=${vital}>
<div class="tab-pane active text-center" id="tab_1_2" th:object=${grith}>
</form>

相关内容

  • 没有找到相关文章

最新更新