【发布时间】:2019-06-14 11:25:07
【问题描述】:
我只是在学习 spring boot 和 thymeleaf,我知道的是在模态表单中进行验证,而不重定向它,只是在这一步混淆。
我的班级模型
public class Class {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty
@NotBlank
private String className;
public Class(@NotEmpty @NotBlank String className) {
this.className = className;
}
}
Html Fronted 显示模态
<div class="modal fade" id="addModal" tabindex="-1" th:fragment="modal-add" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Classroom</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form th:action="@{/addclass}" th:object="${class}" method="post">
<div class="modal-body">
<div class="form-group">
<label for="className">Class Name</label>
<input type="text" class="form-control" id="className" th:field="*{className}" placeholder="Name of Class">
<div class="text text-danger" th:if="${#fields.hasErrors('className')}" th:errors="*{className}">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" value="Save" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
类控制器
@PostMapping("/addclass")
public String addClass(@Valid @ModelAttribute("class") Class kelas, BindingResult result) {
if(result.hasErrors()) {
//what to do here ? to show error validation without closing modal?
}else{
classService.addClass(kelas);
}
return "redirect:/classlist";
}
【问题讨论】:
-
我不确定您是否可以按照自己的方式进行操作。但是您可以尝试使用
ajax -
返回您要渲染的视图的名称(没有
redirect:,所有内容都将被保留。另外我强烈建议为您的班级提供另一个名称然后Class,就像某处它会让你失败,你会使用错误的课程。
标签: jquery spring spring-boot bootstrap-4 thymeleaf