我使用Spring MVC与Hibernate验证器4.2.0。有我的类路径上的ValidationMessages.properties在/WEB-INF/classes/ValidationMessages.properties:Spring MVC Hibernate Validator TypeMismatch异常
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。来自类路径的属性很好。我的控制器:
@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,但没有任何区别。有任何想法吗?
我使用构造器注入,而不是自动连接时,但我得到: 未能java.lang.String类型的属性值转换为属性字段名需要java.lang.Integer类型;嵌套的异常是java.lang.NumberFormatException:对于输入字符串:“A” – JimJay
看起来像我的bean定义的问题? – JimJay
你的bean定义看起来很好。你使用getDefaultMessage()来获取错误信息吗? –