我使用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()來獲取錯誤信息嗎? –