本文介绍了在多个类的spring MVC控制器中应用自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注册页面使用自定义valiadtor

I have one registration page which uses custom valiadtor

public class CustomValidator implements Validator {

    private Validator validator;

    public CustomValidator(Validator validator) {
        this.validator = validator;
    }

    @SuppressWarnings("rawtypes")
    public boolean supports(Class clazz) {
        return Registration.class.equals(clazz);
    }

    public void validate(Object target, Errors errors) {

        validator.validate(target, errors);



        Registration myModel1 = (Registration) target;
        if (! myModel1.getConfirm_password().equals(myModel1.getPassword())) {
            errors.rejectValue("confirm_password", "confirm_password.confirm");
        }

    }
}

问题是我想在两个表格上应用它,所以我很困惑如何用两个类编写这个函数。此功能现在只有注册类。如果我也想要其中的Person类怎么办?

The problem is that i want to apply it on two forms so i am confused how to write this function with two classes. This function now has only Registration class . what if i also want Person class in it as well

public boolean supports(Class clazz) {
        return Registration.class.equals(clazz);
    }

我可以在该函数中编写多个类

Can i write multiple classes in that function

这里是我的控制器

@InitBinder
    public void initBinder(final WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
        Validator validator = (Validator) binder.getValidator();
        binder.setValidator(new CustomValidator((org.springframework.validation.Validator) validator));
    }


推荐答案

你可以这样做

public boolean supports(Class clazz) {
    return Registration.class.equals(clazz) || Another.class.equals(clazz);
}

然后你的验证应该做这样的事情

Then your validate should do something like this

    public void validate(Object target, Errors errors) {
    validator.validate(target, errors);

    String password = null;
    String confirm = null;
    if (target instanceof Registration) {
        Registration registration = (Registration) target;
        password = registration.getPassword();
        confirm = registration.getConfirm_password();
    } else if (target instanceof Another) {
        Another another = (Another) target;
        password = another.getPassword();
        confirm = another.getConfirm_password();
    }
    if (! confirm.equals(password())) {
        errors.rejectValue("confirm_password", "confirm_password.confirm");
    }

}

我认为你不应该使用它可能最好用于分离类更好的可读性,并降低复杂性。在验证器中引入层次结构或模型对象(Vistor模式)不是最佳解决方案。

I don't think you should use this probably it is better to use to separate classes is better for readability, and reduces complexity. To introduce hierarchy in your validators or Model objects (Vistor pattern) is not the best solution.

这篇关于在多个类的spring MVC控制器中应用自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 09:00