gpt4 book ai didi

java - Spring MVC 中的自定义 validator 注解

转载 作者:行者123 更新时间:2023-11-30 10:07:44 24 4
gpt4 key购买 nike


我为 <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
请告诉我如何更正此消息。

最佳答案

您能否按照 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/

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