Spring MVC中的自定义验证器注释

时间:2019-01-09 05:50:49

标签: java spring-validator


我为<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;

验证工作正常。。但是问题是验证方法也附加了另一条消息。 validation view
请告诉我如何更正此消息。

1 个答案:

答案 0 :(得分:0)

您可以尝试按照https://stackoverflow.com/a/53371025/10232467

中的说明更改控制器中Validator的实现吗?

所以您的控制器方法可以像

@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对象。在验证器中替换

errors.rejectValue("country",  "This value is cannot be empty");

errors.rejectValue("defaultcustomer.country",  "This value is cannot be empty");

还发现,应将Customer类修改为

@Valid
private Country country;