gpt4 book ai didi

spring - 如何在MultiActionController中执行Spring验证?

转载 作者:行者123 更新时间:2023-12-02 06:30:50 24 4
gpt4 key购买 nike

如何在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 定义了一个名为 validators 的属性,您应该在其中提供 MultiActionController 使用的任何Validator 。在这里你可以看到一段代码,它负责验证 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 - 如何在MultiActionController中执行Spring验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2744587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com