【发布时间】:2023-04-06 06:55:01
【问题描述】:
我刚开始使用 javax.validation.constraints 测试验证,我认为我做的一切都很好,但不知何故无法正常工作。我正在查看我的代码很长时间,但找不到任何问题。当我输入错误的名称数据以形成和提交时,错误文本不会弹出,并且 (errors.hasErrors()) 是错误的,表示没有任何错误。
这是我的课:
@Data
public class Application {
private int id;
@NotNull(message = "Nazwa wymagana!")
@Size(min=2, message = "Name should have at least 2 characters!")
@Size(max=30, message = "Name too long!")
private String name;
private String domain;
private List<Person> users;
}
控制器:
@GetMapping("applications/new")
public String addAppSetup(Model model){
model.addAttribute("app", new Application());
return "applications-add";
}
@PostMapping("/applications/add")
public String addApp(@Valid Application app, Model model, Errors errors){
if(errors.hasErrors()){
return "applications-add";
}
applicationService.addApplication(app);
model.addAttribute("apps", applicationService.getApplications());
return "redirect:/applications";
}
表格:
<form action="#" th:action="@{/applications/add}" th:object="${app}" method="post">
<div th:if="${#fields.hasErrors()}">
<span>
Proszę popraw błędy i spróbuj ponownie.
</span>
</div>
<div>
<label for="nameeee">Nazwa aplikacji</label>
<input type="text" th:field="*{name}" id="nameeee" placeholder="Nazwa"/>
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
</div>
<div>
<label for="domain">Domena aplikacji</label>
<input type="text" th:field="*{domain}" id="domain" placeholder="Domena"/>
</div>
<input type="submit" value="Dodaj aplikację!">
</form>
【问题讨论】:
-
更详细地描述“不工作”。
-
什么是错误和模型?在您提供的代码中似乎一切正常。
标签: java spring spring-boot spring-mvc thymeleaf