我为 <form:select>
创建了自定义验证填充国家/地区列表。
Customer.jsp
Country:
<form:select path="country" items="${countries}" />
<form:errors path="country" cssClass="error"/>
FomeController.java
@RequestMapping(value = "/customer", method = RequestMethod.POST)
public String prosCustomer(Model model,
@Valid @ModelAttribute("defaultcustomer") Customer customer,
BindingResult result
) {
CustomerValidator vali = new CustomerValidator();
vali.validate(customer, result);
if (result.hasErrors()) {
return "form/customer";
} else {
...
}
}
CustomValidator.java
public class CustomerValidator implements Validator {
@Override
public boolean supports(Class<?> type) {
return Customer.class.equals(type);
}
@Override
public void validate(Object target, Errors errors) {
Customer customer = (Customer) target;
int countyid=Integer.parseInt(customer.getCountry().getCountry());
if (countyid==0) {
errors.rejectValue("country", "This value is cannot be empty");
}
}
}
Customer.java
private Country country;
最佳答案
您能否按照 https://stackoverflow.com/a/53371025/10232467 中的说明尝试更改 Controller 中 Validator 的实现?
所以你的 Controller 方法可以像
@Autowired
CustomerValidator customerValidator;
@InitBinder("defaultcustomer")
protected void initDefaultCustomerBinder(WebDataBinder binder) {
binder.addValidators(customerValidator);
}
@PostMapping("/customer")
public String prosCustomer(@Validated Customer defaultcustomer, BindingResult bindingResult) {
// if error
if (bindingResult.hasErrors()) {
return "form/customer";
}
// if no error
return "redirect:/sucess";
}
此外,jsp中的表单模型名称应定义为“defaultcustomer”
编辑:
我错过了 Customer 类中嵌套的 Country 对象。在 validator 中替换
errors.rejectValue("country", "This value is cannot be empty");
与
errors.rejectValue("defaultcustomer.country", "This value is cannot be empty");
还发现Customer类应该修改为
@Valid
private Country country;
关于java - Spring MVC 中的自定义 validator 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103976/