Spring-boot BindingResult没有出错

时间:2017-09-07 08:51:55

标签: spring hibernate validation spring-data

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

我的销售有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的DTO使用SalesViewDTO

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结果为空?

1 个答案:

答案 0 :(得分:2)

将@Valid添加到SaleViewModel的销售内部对象

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

验证嵌套对象也是必要的。