gpt4 book ai didi

java - java spring如何自定义@NotNull验证错误信息

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:15 26 4
gpt4 key购买 nike

    @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;

大家好,我正在尝试验证 channel 参数,使其不为空。如果我将它解析为空,它只会抛出我:

{
"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

关于java - java spring如何自定义@NotNull验证错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55277013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com