简体   繁体   English

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

[英]Custom Validator Annotation in Spring MVC


I created a custom validation to <form:select> that populate country list. 我为<form:select>创建了一个自定义验证,以填充国家/地区列表。


Customer.jsp Customer.jsp

    Country: 
    <form:select path="country" items="${countries}" />
    <form:errors path="country" cssClass="error"/>

FomeController.java 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 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 Customer.java

   private Country country;

Validation is working perfectly fine. 验证工作正常。 But the problem is that the validation method has attached another message too. 但是问题是验证方法也附加了另一条消息。 验证视图
Please tell me how to correct this message. 请告诉我如何更正此消息。

Can you try changing the implementation of Validator in controller as explained in https://stackoverflow.com/a/53371025/10232467 您是否可以按照https://stackoverflow.com/a/53371025/10232467中的说明更改控制器中Validator的实现

So you controller method can be like 所以你的控制器方法可以像

@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";
}

Additionally the form model name in jsp should be defined as "defaultcustomer" 此外,jsp中的表单模型名称应定义为“ defaultcustomer”

EDIT : 编辑:

I missed the nested Country object in Customer class. 我错过了Customer类中的嵌套Country对象。 In validator replace 在验证器中替换

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

with

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

Also found that Customer class should be modified as 还发现应将Customer类修改为

@Valid
private Country country;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM