Spring Validation 自定义消息 - 字段名称

标签 spring hibernate validation spring-mvc

问题:如何在 Spring 中获取验证消息中的字段名称

有没有办法可以访问 ValidationMessages.properties 文件中的字段名称,例如下面我尝试使用 {0} 但它不起作用,我在某处见过它。我希望 Spring 动态地将字段名称放在那里,这样我就不必为每个类重复它。

public class RegistrationForm {

    @NotEmpty(message = "{NotEmpty}")
    private String email;


    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

ValidationMessages.properties
NotEmpty={0} TEST

最佳答案

如果您使用 Spring 消息包(即 message.properties )而不是 ValidationMessages.properties,这是可能的本地化消息。

使用您的示例,Spring 将(在第一次通过时)尝试使用 messages.properties 中的以下消息键(或代码)本地化字段名称。 :

[RegistrationForm.email,email]

如果未找到任何内容,则回退到字段名称。

Spring 然后使用以下键查找本地化的错误消息本身:
[NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]

注意这里NotEmpty更高 优先级高于 java.lang.String,NotEmpty因此,如果您想根据字段类型自定义消息,请不要上当。

所以如果你把以下内容放在你的messages.properties中,您将获得所需的行为:
# for the localized field name (or just email as the key)
RegistrationForm.email=Registration Email Address
# for the localized error message (or use another specific message key)
NotEmpty={0} must not be empty!

来自 SpringValidatorAdapter#getArgumentsForConstraint() 的 javadoc :

Return FieldError arguments for a validation error on the given field. Invoked for each violated constraint.

The default implementation returns a first argument indicating the field name (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes). Afterwards, it adds all actual constraint annotation attributes (i.e. excluding "message", "groups" and "payload") in alphabetical order of their attribute names.

Can be overridden to e.g. add further attributes from the constraint descriptor.



同时与 ValidationMessages.properties你会用 {max}引用max @Size 的属性注释,对于 Spring 消息包,您将使用 {1} (因为 max@Size 按字母顺序排列的第一个属性)。

有关更多信息,您还可以查看我对 ease field name localization 的功能请求.

附录:如何找到这些信息?

不幸的是,通过介入代码(现在是这篇文章!)。

要找出哪些键用于定位错误字段,请检查 BindingResult 的值。 .在您的示例中,您会收到此错误:
Field error in object 'RegistrationForm' on field 'email': rejected value []; codes [NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [RegistrationForm.email,email]; arguments []; default message [email]]; default message [may not be empty]
SpringValidatorAdapter#getArgumentsForConstraint()负责使验证注释属性值和字段名称可用于错误消息。

关于Spring Validation 自定义消息 - 字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34249937/

相关文章:

java - 没有错误,但是映射不起作用 Spring boot + tomcat 8.0

php - 正则表达式验证以包含 jquery 的 Enter 键

java - Java 8时间包的Spring Batch序列化问题

java - 可以使用 Postgres 序列和 Hibernate 映射制作可查询的计数器吗?

java - HTTP 请求之间的 Hibernate session

spring - PostgreSQL hibernate 和 Spring

java - 我应该将 Bean 验证与 EJB 3.1、JSF2.0 和 JPA 一起使用吗?

java - 如何限制 JTable 中的输入?

Java健康检查最佳实践

spring - ActiveMQ 未释放队列的磁盘存储空间