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

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

最佳答案

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

相关文章:

java stringbuilder删除一行

java - Android程序设计错误

java - 如何在可扩展 ListView 适配器的 getChildView() 中增加和减少点击监听器中的计数值?

使用 Gson 将 BindingResult 转换为 JSON 时出现 java.lang.StackOverflowError

java - Spring validator 自定义 HTTP 状态

java - Android Studio Java - 第一个数组显示第二个数组的索引值

java - JPMS 是否支持来自 META-INF/services 的自动模块服务?

spring-mvc - spring 验证器不使用属性文件来显示错误消息

java - Spring WebFlow - 两个字段的一次验证

spring - 如何 : Spring get rid of @Validate for automatic Controller validation?