将Javax验证与JavaFX集成

时间:2018-09-13 12:40:27

标签: java spring spring-boot javafx bean-validation

我已经在多个Spring MVC项目中工作,可以像这样简单地完成验证:

CONTROLLER

@RequestMapping(value = {"/newHeightUnit"}, method = RequestMethod.POST)
public String saveHeightUnit(@Valid HeightUnit heightUnit, BindingResult result, ModelMap model) 
{
    boolean hasCustomErrors = validate(result, heightUnit);
    if ((hasCustomErrors) || (result.hasErrors()))
    {
        setPermissions(model);

        return "heightUnitDataAccess";
    }
    heightUnitService.save(heightUnit);
    session.setAttribute("successMessage", "Successfully added height unit \"" + heightUnit.getName() + "\"!");
    return "redirect:/heightUnits/list";
}

private boolean validate(BindingResult result, HeightUnit heightUnit)
{
    boolean hasCustomErrors = false;
    if (heightUnitService.nameExists(heightUnit))
    {
        FieldError error = new FieldError("heightUnit", "name", heightUnit.getName(), false, null, null, 
                heightUnit.getName() + " already exists!");
        result.addError(error);
        hasCustomErrors = true;
    }
    return hasCustomErrors;
}

这将针对实体具有的任何验证批注(@ NotNull,@ Size,@ Digits等)来验证实体。

如何在JavaFX中实现相同的目的?正如我在MVC项目中所做的那样,我有9个实体全部带有验证注释。我将Spring与您可以称为视图/服务/ dao结构的一起使用。我根本不使用FXML,我的UI组件都是用纯Java生成的,我打算保持这种状态。

如何以类似于Spring MVC的友好方法在实体上使用验证注释?

说明

仅供参考,这是当前保存我的实体的方式。添加用户输入时,目前尚无任何验证,但一切正常。我的实体都已注解,可以使用了,我只是想学习如何将优秀的@Valid整合到组合中:

@Override
public void saveEntity() 
{
    TextField nameField = (TextField)formFields.get(0);

    try
    {
        Category newCategory = new Category(null, nameField.getText(), new Date(), null);
        categoryService.save(newCategory);
    }
    catch (Exception ex)
    {
        logger.error("Error adding category : " + ex.getMessage());
    }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

所以我最终得到了一个非常干净的结果。首先,我结束了一个看起来像这样的验证器类:

public class EntityValidator 
{
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    public Set<ConstraintViolation<Category>> validateCategory(Category category)
    {
        return validator.validate(category);
    }
}

我正在使用Spring使此类可用于自动装配:

@Bean
public EntityValidator entityValidator()
{
    return new EntityValidator();
}

bean验证如下:

TextField nameField = (TextField)formFields.get(0);

    try
    {
        Category newCategory = new Category(null, nameField.getText(), new Date(), null);

        Set<ConstraintViolation<Category>> errors = validator.validateCategory(newCategory);

        if (errors.isEmpty())
        {
            categoryService.save(newCategory);

            close();
        }
        else
        {
            showErrorMessages(errors);
        }
    }
    catch (Exception ex)
    {
        logger.error("Error adding category : " + ex.getMessage());
    }

showErrorMessages方法仅接受错误Set并在错误对话框中显示第一个错误。由于我使用的是验证组,因此Set中不会出现多个错误,因此看起来很干净。它永远不会像从Web项目中的控制器那样简单,但是我对总体结果感到非常满意。

欢呼