在春季使用自定义验证器时,如何在错误消息中获取无效值? [英] How to get the Invalid value in the error message while using custom validator in spring?

查看:97
本文介绍了在春季使用自定义验证器时,如何在错误消息中获取无效值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在错误消息中显示无效值 我有messages.properties文件,如下所示

I having trouble in showing Invalid value in the error message I have messages.properties file as follows

ProductId.exists.custom.validator.validation = A product already exists with product id ${validatedValue}.

以下是我的自定义验证程序界面

and following is my custom validtor interface

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = ProductIdValidator.class)
@Documented
public @interface ProductId {
   String message() default "{ProductId.exists.custom.validator.validation}";

    Class<?>[] groups() default {};

    public abstract Class<? extends Payload>[] payload() default {};
}

这是实现

@Component
public class ProductIdValidator implements ConstraintValidator<ProductId, String>{

    @Autowired
    private ProductService productService;

    @Override
    public void initialize(ProductId constraintAnnotation) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Product product = productService.getProductById(value);
        if(product!= null) {
            return false;
        }
        return true;
    }

}

当我运行我的应用程序时,我收到类似以下的错误消息 A product already exists with product id ${validatedValue}.,但我希望将A product already exists with product id P1234.作为错误消息

When I am running my application I am getting error message like A product already exists with product id ${validatedValue}. but I am expecting A product already exists with product id P1234. as error message

如何在错误消息中获取validatedValue?

How to get the validatedValue in error message?

其他详细信息 我已经使用了hibernate-validator:4.3.1.Final版本和spring-webmvc:3.2.0.RELEASE 而且我在上下文中触发了验证,如下所示:

Additional details I have used hibernate-validator:4.3.1.Final version and spring-webmvc:3.2.0.RELEASE And I am triggering the validation in the context as follows

<mvc:annotation-driven validator="validator"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource" />
</bean>

推荐答案

我不确定我在项目中使用此解决方案的主要原因是–是使插值有效,还是仅使用 ReloadableResourceBundleMessageSource (支持UTF-8中的属性和运行时重载!),而不是默认值.但是,这应该对您有用.

I’m not sure what was the main reason for this solution I’ve used in my project – if to make interpolation work, or just use ReloadableResourceBundleMessageSource (that supports properties in UTF-8 and runtime reloading!) instead of the default one. However, this should work for you.

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" primary="true"
      p:messageInterpolator-ref="messageInterpolator" />

<!-- Hibernate Validator which can interpolate the value being validated in the constraint message -->
<bean id="messageInterpolator" class="ValueFormatterMessageInterpolatorFactoryBean"
      p:messageSource-ref="validatorMessageSource" />

<bean id="validatorMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
      p:basename="classpath:/config/i18n/validator-messages"
      p:defaultEncoding="utf-8"
      p:cacheSeconds="0" />

和自定义的ValueFormatterMessageInterpolatorFactoryBean类:

/**
 * {@linkplain FactoryBean} that creates {@link ValueFormatterMessageInterpolator}
 * with underlying {@link ResourceBundleMessageInterpolator} that uses the given
 * {@link MessageSource}.
 */
public class ValueFormatterMessageInterpolatorFactoryBean implements FactoryBean<MessageInterpolator> {

    private MessageSource messageSource;

    public MessageInterpolator getObject() throws Exception {
        ResourceBundleLocator resourceBundleLocator = new MessageSourceResourceBundleLocator(messageSource);
        return new ValueFormatterMessageInterpolator(
                new ResourceBundleMessageInterpolator(resourceBundleLocator));
    }

    public Class<?> getObjectType() {
        return ValueFormatterMessageInterpolator.class;
    }

    public boolean isSingleton() {
        return true;
    }

    @Required
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}

注意:我正在使用Hibernate Validator 4.3.0.Final.

Note: I’m using Hibernate Validator 4.3.0.Final.

这篇关于在春季使用自定义验证器时,如何在错误消息中获取无效值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆