spring mvc验证消息

时间:2015-09-08 14:56:16

标签: spring validation spring-mvc

我在确定如何将验证属性从spring传递到外部化消息时遇到了问题。我使用的是spring 4,已经包含了#34; validation-api-1.1.0.Final"和" hibernate-validator-5.2.1.Final"。

我的模特:

@Size(min=20, max=64)
private String email;

我仍然收到消息" 电子邮件不应为空TCH {2} {1} {0} "当我回到表格。

我的validationMessages.properties中包含以下行:

  • Size.virement.email =电子邮件不应为空TCH {2} {1} {0}

我还尝试使用 {min} {max} ,以及%1 %0 。这些都不起作用。

我对spring的xml配置有以下配置:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>classpath:content/ValidationMessages</value>
                <value>classpath:content/Language</value>
                ...
            </list>
        </property>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

我也确实包含了 spring-context-4.1.5.RELEASE 库。

任何想法??
请注意,我使用百里香来渲染视图。

提前谢谢。

2 个答案:

答案 0 :(得分:0)

您基本上有一个错误消息模板,您希望使用给定约束的值填充它。

我认为您可以使用自定义ConstraintValidor实现此目的。

请参阅此处的Hibernate参考,尤其是3.1.2.1节: https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html

我希望它能给出一些想法!

答案 1 :(得分:0)

尝试添加:

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

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

示例:

Size.user.name=Invalid username

请注意,user ModelAttribute中的Controller值为@ModelAttribute("user")User.save_data_from_api

相关问题