2017-01-09 99 views
1

我在Spring MVC項目(Spring Boot 1.4.2)的表單對象中使用了javax.validation.constraints.AssertTrue註解。Spring驗證@AssertTrue自定義錯誤代碼/消息

我的班級與此類似:

public class CommandForm { 

    @NotEmpty 
    @Email 
    private String email; 

    // ... 

    @AssertTrue(message="{error.my.custom.message}") 
    public boolean isValid(){ 
     // validate fields 
    } 
} 

方法isValid正確調用和驗證過程中正常工作,但我的自定義錯誤代碼沒有被正確解析。

我在我的message.properties文件中有error.my.custom.message字段,但是當驗證失敗時,我將"{error.my.custom.message}"字符串作爲錯誤消息而不是解析的消息。

我的代碼有什麼問題?這是設置自定義錯誤代碼的正確語法嗎?

回答

0

我搜了一下調試後的溶液。

設置自定義消息的最簡單方法是簡單地在我的message.properties中定義一個AssertTrue.commandForm.valid字段。

不需要在@AssertTrue註釋中設置message參數。

0

我認爲唯一的問題是,默認情況下,Java Validation API (JSR-303)會從名爲ValidationMessages.properties(在/resources下)的文件中讀取這些消息。

創建一個帶有該名稱的文件並將消息移到那裏......然後再試一次。它應該工作!

NOTE:雖然您可以更改文件名,但「按慣例」就是這樣命名的。

1

移動郵件到ValidationMessages.properties文件 或覆蓋您的WebMvcConfigurerAdaptergetValidator()方法,使您的自定義message.properties彈簧得到加載,如下所示:

import org.springframework.context.MessageSource; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.support.ResourceBundleMessageSource; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.validation.Validator; 
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 

@Configuration 
public class WebController extends WebMvcConfigurerAdapter { 

    @Override 
    public Validator getValidator() { 
     LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); 
     validator.setValidationMessageSource(messageSource()); 
     return validator; 
    } 

    @Bean(name = "messageSource") 
    public MessageSource messageSource() { 
     ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 
     messageSource.setBasename("message"); 
     messageSource.setDefaultEncoding("UTF-8"); 
     return messageSource; 
    } 

}