簡體   English   中英

Spring MVC中的自定義驗證器注釋

[英]Custom Validator Annotation in Spring MVC


我為<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中的說明更改控制器中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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM