簡體   English   中英

如何自定義java spring @NotNull驗證錯誤信息

[英]How to customize java spring @NotNull validation error message

    @POST
    @Path("")
    @Consumes({"application/x-www-form-urlencoded"})
    TokenDTO login(@ApiParam(value = "The id of the channel used", required = true )  @HeaderParam("channel")  @NotEmpty(message = "email.notempty") String channel) throws Exception;

大家好,我正在嘗試驗證通道參數,因此它不是空的。 如果我把它解析為空它只會拋出我:

{
"code": 26,
"message": "Validation Error: :NotEmpty",
"data": [
    {
        "type": "NotEmpty",
        "property": "",
        "value": null,
        "inputType": "body",
        "attributes": null
    }
],
"source": "XXXX",
"type": "ValidationException",
"guid": "965ee91a-99a1-4ae5-b721-6415a80dad23"
}

您能否告訴我如何自定義驗證錯誤消息?

編輯:我看過許多文章描述我如何自定義“字段”驗證的消息。 但我想驗證方法參數。

在你的參數中確保添加花括號,所以它將是這樣的

@NotEmpty(message = "{email.notempty}") String email

然后,在應用程序配置中定義LocalValidatorFactoryBean:

   @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:ValidationMessages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

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

最后,在類路徑中創建一個ValidationMessages.properties文件,其中包含:

email.notempty=E-mail address is required

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM