如何在MultiActionController中执行Spring验证?

如何在MultiActionController中执行Spring验证?

解决方法:

让我们写以下

public class Person {

    private String name;
    private Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

还有你的MultiActionController

import static org.springframework.validation.ValidationUtils.*;

@Component
public class PersonController extends MultiActionController {

    public PersonController() {
        setMethodNameResolver(new InternalPathMethodNameResolver());

        setValidators(new Validator[] {new Validator() {
            public boolean supports(Class clazz) {
                return clazz.isAssignableFrom(Person.class);
            }

            public void validate(Object command, Errors errors) {
                rejectIfEmpty(errors, "age", "", "Age is required");
                rejectIfEmptyOrWhitespace(errors, "name", "", "Name is required");
            }

        }});
    }

    public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Person person) throws Exception {
        // do something (save our Person object, for instance)

        return new ModelAndView();
    }

}    

MultiActionController定义了一个称为验证器的属性,您应该在其中提供MultiActionController使用的任何验证器.在这里,您可以看到一段代码,该代码负责验证MultiActionController中的Command对象

ServletRequestDataBinder binder = ...

if (this.validators != null) 
    for (int i = 0; i < this.validators.length; i++) {
        if (this.validators[i].supports(command.getClass())) {
    ValidationUtils.invokeValidator(this.validators[i], command, binder.getBindingResult());
        }
    }
}

/**
  * Notice closeNoCatch method
  */
binder.closeNoCatch();

closeNoCatch方法说

Treats errors as fatal

因此,如果您的验证器返回任何错误,closeNoCatch将抛出ServletRequestBindingException.但是,您可以在MultiActionController方法中捕获它,如下所示

public ModelAndView hanldeBindException(HttpServletRequest request, HttpServletResponse response, ServletRequestBindingException bindingException) {
    // do what you want right here

    BindException bindException = (BindException) bindingException.getRootCause();

    return new ModelAndView("personValidatorView").addAllObjects(bindException.getModel());
}

为了测试,让我们做以下一个

@Test
public void failureValidation() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setRequestURI("http://127.0.0.1:8080/myContext/person/add.html");

    /**
     * Empty values
     */
    request.addParameter("name", "");
    request.addParameter("age", "");

    PersonController personController = new PersonController();

    ModelAndView mav = personController.handleRequest(request, new MockHttpServletResponse());

    BindingResult bindingResult = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + "command");

    /**
     * Our Validator rejected 2 Error
     */
    assertTrue(bindingResult.getErrorCount() == 2);
    for (Object object : bindingResult.getAllErrors()) {
        if(object instanceof FieldError) {
            FieldError fieldError = (FieldError) object;

            System.out.println(fieldError.getField());
        }
    }
}
上一篇:Spring MVC 3.如何在绑定之后但在验证之前修改表单


下一篇:php-Laravel:如何验证变量是数组还是匹配正则表达式的字符串