3

Hibernate validator 4.2.0에서 Spring MVC를 사용하고있다. /WEB-INF/classes/ValidationMessages.properties 내 클래스 경로에 ValidationMessages.properties이 :이 javaconfig에서 빈으로 사용할 수 있습니다Spring MVC Hibernate Validator TypeMismatch 예외

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

: ValidationMessages를로드

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

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

합니다. 속성은 클래스 경로에서 잘. 내 컨트롤러 :

@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 예외 오류를, (I 메시지 소스를 사용하지 않고 수동으로 오류 메시지를 삽입)와 예외 :

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" 

보다는 DataBinder 내 된 MessageSource를 사용하지 않는 것처럼 보인다 ValidationMessages.properties에서, 그래서 코드 (?). 예외 메시지보다는 속성 파일에서 typeMismatch 코드를 원합니다. 나는 또한 ReloadableResourceBundleMessageSource 대신 ResourceBundleMessageSource를 시도했지만 아무런 차이가 없었다. 어떤 아이디어?

답변

2

어떻게 오류 메시지가 나타 납니까? 이게 너에게 효과가 있니?

@Autowired 
private MessageSource messageSource; 
... 

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

차라리 autowire가보다 생성자 주입을 사용하고 있습니다,하지만 난 얻을 : 는 재산의 필드 명 필수 유형 java.lang.Integer의에 java.lang.String 타입의 속성 값을 변환 할 수 없습니다; 중첩 예외는 java.lang.NumberFormatException : 입력 문자열 : "A" – JimJay

+0

내 bean 정의에 문제가있는 것 같습니까? – JimJay

+0

bean 정의가 잘된 것 같습니다. getDefaultMessage()를 사용하여 오류 메시지를 가져 옵니까? –

관련 문제