简体   繁体   English

Hibernate Validator + Spring:关于验证错误的错误消息

[英]Hibernate Validator + Spring: incorrect message on validation error

I wrote a custom Hibernate validation constraint for Money class: 我为Money类编写了一个自定义的Hibernate验证约束:

@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = MoneyLimitedValidator.class)
@Documented
public @interface MoneyLimited {
    String message() default "{error.validation.money.limited}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

It works fine except error message. 它工作正常,但错误消息除外。 I see very strange behaviour: resource bundle found and message resolved by name, but it wrapped into special chars which usually appears if message can't be resolved by name: 我看到一个非常奇怪的行为:找到了资源束,并按名称解析了消息,但是它包装在特殊字符中,如果不能按名称解析消息,通常会出现这些字符:

??Incorrect sum value._en_EN??

Here Incorrect sum value. 此处的Incorrect sum value. is a correct message, which is accepted by name error.validation.money.limited . 是正确的消息,被名称error.validation.money.limited接受。 Originaly my message looks so: 原来我的消息看起来像这样:

error.validation.money.limited = Incorrect sum value.

I tried to remove {} braces from message name into MoneyLimited#message() , but nothing changes (even more strange). 我试图将消息名称中的{}大括号删除到MoneyLimited#message() ,但没有任何变化(甚至更奇怪)。

I specified my validation message bundle as described in this answer : 我按照此答案中的说明指定了验证消息束:

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

So the question is: how to fix message? 所以问题是:如何修复消息?

I'm using Spring Framework 3.2.4.RELEASE and Hibernate Validator 4.3.1.Final . 我正在使用Spring Framework 3.2.4.RELEASEHibernate Validator 4.3.1.Final

I'm found the reason of double resolving. 我找到了双重解决的原因。 I didn't mentioned before, that I'm using Thymeleaf as template engine (which is using SpringEL ). 我之前没有提到,我正在使用Thymeleaf作为模板引擎(正在使用SpringEL )。 There are an useful snippet in example app, which I just copy-paste (shame on me) and forgot about: 示例应用程序中有一个有用的代码段,我只是复制粘贴(对我感到羞耻)而忘记了:

<div class="errors" th:if="${#fields.hasErrors('*')}" th:fragment="validationErrorTpl">
    <ul>
        <li th:each="err : ${#fields.errors('*')}" th:text="#{${err}}">Input is incorrect</li>
    </ul>
</div>

As you can see ${err} variable enclosed in #{} , which is actually resolving message from bundle. 如您所见, ${err}变量包含在#{} ,它实际上是从包中解析消息。 So with braces in validation constraint, message was resolved twice: on annotation level and in view template. 因此,在验证约束中使用大括号,可以将消息解析两次:在注释级别和视图模板中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM