Spring MVC Hibernate Validator TypeMismatch Exception

时间:2013-05-17 12:29:37

标签: spring validation spring-mvc hibernate-validator spring-mvc-initbinders

我正在使用Spring MVC和Hibernate验证器4.2.0。在/WEB-INF/classes/ValidationMessages.properties中的类路径上有一个ValidationMessages.properties:

typeMismatch.java.lang.Integer=Must specify an integer value.
typeMismatch.int=Invalid number entered
typeMismatch=Invalid type entered

这在javaconfig中以bean的形式提供:

@Configuration
@EnableWebMvc
public class WebApplicationConfiguration extends WebMvcConfigurerAdapter {
...

@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource resourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
    resourceBundleMessageSource.setBasename("ValidationMessages");
    return resourceBundleMessageSource;
}
...

从类路径中加载ValidationMessages.properties。我的控制器:

@Controller
public class myController {
...

@InitBinder("myForm")
protected void initUserBinder(WebDataBinder binder) {
    binder.setValidator(new CustomValidator());
}
...

@ResponseBody
@RequestMapping(value = "/ajax/myRequest", method = RequestMethod.POST)
public CustomResponse ProcessAjaxRequest(
        @Valid @ModelAttribute final MyForm myForm,
        final BindingResult bindingResult)
                throws Exception {

    if (bindingResult.hasErrors()) {
        return new CustomResponse(bindingResult.getAllErrors());
    } else {
        ..
    }
}
...

自定义验证器:

public class CustomValidator implements Validator {

@Override
public boolean supports(Class c) {
    return MyForm.class.equals(c);
}

@Override
public void validate(Object obj, Errors errors) {
..

使用我的CustomValidator进行验证工作正常(我手动插入错误消息,而不是使用消息源),但是对于绑定typeMismatch错误,我得到了异常:

Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'myField'; nested exception is java.lang.NumberFormatException: For input string: "A"

而不是ValidationMessages.properties中的代码,所以看起来好像DataBinder(?)没有使用我的messageSource。我想从我的属性文件而不是异常消息中获取typeMismatch代码。我也尝试使用ResourceBundleMessageSource而不是ReloadableResourceBundleMessageSource,但这没有任何区别。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您如何收到错误消息?这对你有用吗?

@Autowired
private MessageSource messageSource;
...

FieldError error = bindingResult.getFieldError("fieldName");
String errorMessage = messageSource.getMessage(error, Locale.getDefault());