如何在spring中使用ValidationUtils

问题描述 投票:0回答:4

我想按如下方式使用 ValidationUtils。但我无法实例化错误对象,因为错误是一个接口。你能告诉我如何在不使用验证器的情况下使其工作吗?

     if(visitorDetails==null)
    {
        Errors errors;
        visitorDetails=new Visitor(); 
        ValidationUtils.rejectIfEmpty(errors, "VisitorInfo", "Selected Visitor Details Not Found");
    }
spring spring-mvc
4个回答
6
投票

阅读此内容:验证...

但是,您必须在类中实现 Validation 接口,然后使用它来验证您的对象,为此,您可以在控制器中自动装配验证器..

这是一个例子:

public class PersonValidator implements Validator {

    /**
    * This Validator validates *just* Person instances
    */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
      }
}

并在您的控制器中:

....

    @Autowired
    private PersonValidator personValidator;

    @InitBinder
    protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder) {
        binder.addValidators(personValidator);
    }
...

4
投票

假设您正在使用 Spring Boot。

如果使用application.properties(在project/src/resources下),请将以下内容放入其中:

spring.messages.basename=validation

现在放置一个validation.properties(在project/src/resources下)并将以下内容(例如)放入其中:

NotEmpty=This field is required.

您的模型(在本例中为 AppUser)应该具有:

private String useremail;
getters/setters;

像这样创建一个组件(类)(示例):

@Component
public class UserAddValidator implements Validator {

@Autowired
private UserService userService;

@Override
public boolean supports(Class<?> aClass) {
    return AppUser.class.equals(aClass);
}

@Override
public void validate(Object o, Errors errors) {
    AppUser user = (AppUser) o;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "useremail", "NotEmpty");

}

}

以下内容将发送至您的控制器:

@RequestMapping(value = "registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") AppUser userForm, BindingResult bindingResult, Model model) {
    useraddValidator.validate(userForm, bindingResult);

    if (bindingResult.hasErrors()) {
        return "userregistration";
    }

    userService.save(userForm);

    model.addAttribute("success", "User " + userForm.getUsername() + " created successfully");
    return "success";

}

最后但并非最不重要的一点,在你看来,类似这样:

       <div class="row">
            <label class="col-md-3" for="useremail">Email-ID</label>
            <div class="col-md-8">
                <spring:bind path="useremail">
                    <div class="form-group ${status.error ? 'has-error' : ''}">
                        <form:input type="text" path="useremail" class="form-control"
                            placeholder="Email-id" autofocus="true"></form:input>
                        <form:errors path="useremail">${emailerror}</form:errors>
                        
                    </div>
                </spring:bind>
            </div>
        </div>

结果应该如下所示:

enter image description here

您可以在此处查看更多验证。


1
投票

如果我正确理解你的问题,你想要获取错误对象。 对于你的情况,我建议采用以下方法。

if(visitorDetails==null)
{
    visitorDetails=new Visitor(); 
    Errors errors = new BeanPropertyBindingResult(visitorDetails, visitorDetails.getClass().getName());
    ValidationUtils.rejectIfEmpty(errors, "VisitorInfo", "Selected Visitor Details Not Found");
}

如果您需要更多帮助,请告诉我。


0
投票
you can use it to make some constraint on some of your field like show error when the field is empty or emptywithspace , this class already contain some static method that can do that 
below an exemple for using ValidationUtils class 

public class UserValidator implements Validator {


    public boolean supports(Class clazz) {
        // TODO Auto-generated method stub
        return Employee.class.equals(clazz);
    }

    public void validate(Object target, Errors errors) {
        // TODO Auto-generated method stub

        ValidationUtils.rejectIfEmpty(errors, "email", "email");
        ValidationUtils.rejectIfEmpty(errors, "password", "password");

        Employee emplo = (Employee) target;

          if(emplo.getEmail() != null && emplo.getEmail()=="aa") {
              errors.rejectValue("email", "email invalide ");

    }
© www.soinside.com 2019 - 2024. All rights reserved.