javax 验证约束在 Spring Boot 中不起作用

标签 java spring-boot validation constraints

我无法在 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/

相关文章:

java - 我的 Java 类是从文件系统的哪个位置加载的?

javascript - 我可以复制/克隆 JavaScript 中的函数吗?

java - 在 Java 中序列化对象时出现 StackOverflowError

java - 使用java以编程方式在keycloak 4.8.3中创建用户

带有 OpenCv : UnsatisfiedLinkError under Eclipse if use spring-boot-devtools 的 Java Spring 启动应用程序

mysql - Hibernate:字段 'id' 没有默认值

python - Django 1.6 AbstractUser m2m 模型验证错误

javascript - 使用 javascript 或 jquery 验证价格范围

java - 除了客户端编码帮助之外,如果在对象为空时抛出 NPE,Kotlin 中的 '!!' 运算符有什么好处?

windows-xp - Windows XP 上 Wiimote(Wii Remote)的 Java API