【问题标题】:Spring-boot BindingResult not getting errorsSpring-boot BindingResult 没有收到错误
【发布时间】:2017-09-07 17:10:06
【问题描述】:

我的 BindingResult 没有收到错误,但它们出现在堆栈跟踪中。

我的 sales 有一个 salesno 的正则表达式:

@Entity
public class Sale {

public Sale() {
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty
@Pattern(regexp = "^S\\d{9}$", message = "Sales number must be in the format S123456789")
private String salesno;

支持 html 以使用 SalesViewDTO 的 DTO

public class SaleViewModel {

private Sale sale = new Sale();

还有控制器:

    @PostMapping("newSale")
public String saleSubmit(@Valid @ModelAttribute("SaleViewModel") SaleViewModel saleViewModel, BindingResult result) {
    if (result.hasErrors()) {
        List<ObjectError> errors = result.getAllErrors();
        for(ObjectError error : errors) {
            System.out.println("This is the error: " +error);
        }
        return "sale";
    } else {
        // Other stuff

如果我尝试提交表单,我会在控制台上收到消息:

ConstraintViolationImpl{interpolatedMessage='Sales number must be in the format S123456789', propertyPath=salesno, rootBeanClass=class com.gmbh.domain.Sale, messageTemplate='Sale number must be in the format S123456789'}

我想知道为什么Binding Result结果为空?

【问题讨论】:

    标签: spring hibernate validation spring-data


    【解决方案1】:

    在 SaleViewModel 的销售内部对象中添加 @Valid

    public class SaleViewModel {
        @Valid
        private Sale sale = new Sale();
    

    还需要验证嵌套对象。

    【讨论】:

    • 如果它太长,我会发布另一个问题,但是你如何让休眠 @UniqueConstraint 错误进入绑定结果,例如:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '123456789'
    • 它不是验证逻辑的一部分。通常会引入自定义注释,例如@UserNotExists 检查所有逻辑dolszewski.com/spring/custom-validation-annotation-in-spring
    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2017-06-27
    • 2011-05-06
    • 1970-01-01
    • 2019-11-18
    • 2018-05-19
    • 2019-09-01
    相关资源
    最近更新 更多