java - Bean 验证组序列不起作用

标签 java spring-mvc bean-validation hibernate-validator

我正在为我的项目使用 spring 4.1、hibernate validator 5.1.3。从过去 2 天开始,我一直在尝试让 GroupSequence 正常工作。我引用了验证文档、博客和 stackoverflow 上发布的一些问题。

请看下面的类。当我从注释中删除 GroupSequence 和组时,所有验证消息都会一起出现,即所有对名称和其他字段的检查都会一起触发。 让我们说对于名称字段——我希望首先验证@NotBlank 和@Size,然后名称应该与模式匹配,最后应该检查@UniqueName 因为数据库调用。

为此,我按照文档和答案中的建议创建了 GroupSequence。但是当触发验证时,只有@NotBlank 和@Size 被触发用于名称。当我从剩余注释中删除组值时,它们开始工作,但所有错误消息都会立即显示,这是我不想要的。

我希望使用 First.class 组指定的注解在 Second.class 验证之前一起触发。我不明白为什么没有触发组指定的验证。

有人可以指导我吗


@GroupSequence({MyForm.class, OrderedChecks.class})
public class MyForm {

  @NotBlank
  @Size(min = 2, max = 40)
  @Pattern(regexp = "^[\\p{Alnum} ]+$", groups = First.class)
  @UniqueName(groups = Second.class)//Custom validation
  private String name;

  @NotBlank
  @Size(min = 2, max = 40)
  private String url;

  @NotBlank
  @Size(max = 100)
  private String imagePath;

  //Custom Validation
  @CheckContent(acceptedType = <someString>, allowedSize=<someval>, dimensions=<someval> groups = Second.class)
  private MultipartFile image

...
}

@GroupSequence(value = {Default.class, First.class, Second.class})
public interface OrderedChecks {}

@Controller
@RequestMapping(value = "/myForm")
public class MyFormController {

    @RequestMapping(method = POST)
    public String completeSignUp(@Valid @ModelAttribute("myForm") final MyForm myForm,
                            BindingResult result, RedirectAttributes redirectAttributes, Model model) {

        if(result.hasErrors()) {
            model.addAttribute(companyDetailsForm);
            //ERROR_VIEW="myForm";
            return ERROR_VIEW;
        }
       // Doing something else.
      return <success view>;
   }
}

最佳答案

使用 Spring 的 @Validated 而不是 @Valid。这将允许您指定组并控制顺序。

将您的 Controller 方法更改为:

@RequestMapping(method = POST)
public String completeSignUp(@Validated(OrderedChecks.class) @ModelAttribute("myForm") final MyForm myForm,
                        BindingResult result, RedirectAttributes redirectAttributes, Model model) {
...
}

请注意,您不需要 @GroupSequence({MyForm.class, OrderedChecks.class})MyForm bean 之上。

关于java - Bean 验证组序列不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626754/

相关文章:

嵌套对象的 Javax 验证 - 不工作

glassfish - JAX-RS 自定义路径参数验证器

JavaFX - 水平字幕文本

java - 委托(delegate)给 Servlet 的 Spring MVC Controller

hibernate - 当 Sessionfactory.getCurrentSession.merge 调用时,ConstraintValidator 中的 @Autowired bean null

java - Spring 4 : How to map RequestMapping URLs to particular controller

java - 在 Spring MVC 应用程序属性文件中使用阿拉伯字符串

java - 读取 Avro 文件给出 AvroTypeException : missing required field error (even though the new field is declared null in schema)

java - 在测量之间创建延迟

JavaFX 对话 - 游戏