@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"
}
能否请您告诉我如何自定义验证错误消息?
编辑:我看过许多文章,描述了如何自定义“字段”验证的消息。 但是我想验证方法参数。
答案 0 :(得分:1)
在您的参数中,请确保添加大括号,就像这样
@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