javax验证约束在Spring Boot中不起作用 [英] javax validation constraints not working in Spring Boot
问题描述
我无法在Spring Boot应用程序中触发诸如@ NotEmpty,@ NotBlank和@NotNull之类的注释。
I cannot get annotations such as @NotEmpty, @NotBlank and @NotNull to fire in my Spring Boot application.
我已遵循以下示例(行家):
I've followed this (maven) example:
>:// spring.io/guides/gs/validating-form-input/
...我看不到我在做什么错。
...and I don't see what I am doing wrong.
POJO:
import javax.validation.constraints.NotBlank;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
@NotBlank
private String collegeCode;
.
.
.
弹簧控制器:
@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的大学对象。
As well as @NotBlank, I have tried @NotEmpty and @NotNull, but the same thing happens. My screen does not validate the input, and allows a college object with an empty collegeCode to be saved.
有趣的是,如果我更改POJO以使用不推荐使用的Hibernate验证器代替...
The interesting thing is if I change my POJO to use the deprecated Hibernate validator instead...
import org.hibernate.validator.constraints.NotBlank;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class College
{
@NotBlank
private String collegeCode;
.
.
.
...然后验证生效,并且屏幕阻止我保存带有空的collegeCode。
...then the validation DOES fire, and the screen prevents me from saving a College object with an empty collegeCode.
有人可以告诉我为什么使用javax.validation.constraints验证程序时我的验证不起作用吗?
Can anyone tell me why my validation doesn't work when using the javax.validation.constraints validators?
推荐答案
自版本2.3.0.RELEASE以来,默认情况下,验证启动器未包含在web / webflux启动器中,您需要手动添加它。更多详细信息此处
Since version 2.3.0.RELEASE the validation starter is not included in web/webflux starters by default, you need to add it manually. More details here
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
这篇关于javax验证约束在Spring Boot中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!