我无法在 Spring Boot 应用程序中触发 @NotEmpty、@NotBlank 和 @NotNull 等注释。
我遵循了这个(maven)示例:
https://spring.io/guides/gs/validating-form-input/
...我不明白我做错了什么。
POJO:
import javax.validation.constraints.NotBlank;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
@NotBlank
private String collegeCode;
.
.
.
Spring Controller :
@RequestMapping(value="/addCollege", method = RequestMethod.POST)
public String addCollege(@Valid @ModelAttribute("college") College college, BindingResult bindingResult, Model model, HttpSession session)
{
if(bindingResult.hasErrors()) //this is never true
{
logger.debug("Errors when adding new college!!!");
return "admin/colleges/addCollege";
}
collegeProcessor.saveCollege(college);
return getAllColleges(model, session);
}
屏幕:
<form action="#" th:action="${addOrEdit} == 'add' ? @{/addCollege} : @{/updateCollege}" th:object="${college}" method="post">
<table class="table">
<tr>
<td>College Code</td>
<td><input size="10" name="collegeCode" th:field="*{collegeCode}"/></td>
<div id="errors" th:if="${#fields.hasErrors('collegeCode')}" th:errors="*{collegeCode}"></div>
</tr>
.
.
.
除了@NotBlank,我还尝试过@NotEmpty和@NotNull,但同样的事情发生了。我的屏幕不验证输入,并允许保存具有空 CollegeCode 的大学对象。
有趣的是,如果我将 POJO 更改为使用已弃用的 Hibernate validator ......
import org.hibernate.validator.constraints.NotBlank;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
@NotBlank
private String collegeCode;
.
.
.
...然后验证确实会触发,并且屏幕阻止我保存具有空 CollegeCode 的 College 对象。
谁能告诉我为什么在使用 javax.validation.constraints validator 时我的验证不起作用?
最佳答案
从 2.3.0.RELEASE 版本开始,默认情况下,验证启动器不包含在 web/webflux 启动器中,您需要手动添加。更多详情here
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
关于javax 验证约束在 Spring Boot 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56527965/