【问题标题】:JSR 303 Bean Validation in SpringSpring 中的 JSR 303 Bean 验证
【发布时间】:2011-07-24 23:34:59
【问题描述】:

这是我的表单豆:-

public class LoginFormBean {

    @NotEmpty
    private String userId;

    @NotEmpty
    private String password;    

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String pass) {
        this.password = pass;
    }
}

在我的 message.properties 文件中我写:-

NotEmpty={0} must not empty.

它向我显示错误消息:userId must not empty.password must not empty.

但我想将错误消息显示为User Id must not empty.'Password must not empty.'

我知道我可以在我的 formBean 中使用@NotEmpty(message="User Id must not empty"),但我想同步消息,就好像我们需要更改消息一样,这样开销会更少。
我已经搜索了 JSR 文档,但没有找到任何东西可以将我的属性名称 userId 替换为 User Id。请大家帮帮我,从两天开始就卡住了。
如果不可能,请告诉我,如果不能,请帮助我做些替代。

谢谢
假货

【问题讨论】:

    标签: spring-mvc properties bean-validation


    【解决方案1】:

    在同一个 message.properties 文件中,您只需添加以下内容:

    userId=User Id
    password=Password
    

    或者您可以为字段名称使用单独的文件,为验证消息代码使用单独的文件。这将更具可读性。

    祝你好运:)

    【讨论】:

      【解决方案2】:

      您现在可能已经解决了这个问题,但是要在 JSR 303 formbeans 上设置错误消息,您需要以下列格式将条目添加到您的属性文件中:

      <Constraint-Name>.<formbean-name>.<attribute-name>=My Message Text
      

      你的情况是:

      NotEmpty.loginFormBean.userId=User Id must not empty
      
      NotEmpty.loginFormBean.password=Password must not empty
      

      其中 loginFormBean 是表单的名称,而不是类名。

      【讨论】:

      • 感谢您的回复,是的,我知道我可以这样使用,但它仍然不能“重复使用”。在这种情况下,我必须为属性文件中的每个属性创建一个新条目,即使我在多个 bean 中使用“userId”属性。
      【解决方案3】:

      作为参考,只需记录BeanPropertyBindingResult 实例并检查日志。对于每个违反验证的属性,您会发现四种不同类型的属性代码。

      这是一个示例日志供参考

      Field error in object 'member' on field 'name': rejected value []; codes [NotEmpty.member.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [member.name,name]; arguments []; default message [name]]; default message [may not be empty]
      

      在上面的日志中你可以找到 codes [NotEmpty.member.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]

      当您没有配置任何错误代码或 spring 找不到匹配的代码时,spring 会使用 DefaultMessageCodesResolver 来解决错误消息。检查java doc 以查看附加错误代码的格式。

      【讨论】:

        猜你喜欢
        • 2013-11-23
        • 2015-01-10
        • 2012-02-08
        • 1970-01-01
        • 2018-08-15
        • 2011-10-29
        • 2014-03-24
        • 2011-01-31
        • 2013-12-27
        相关资源
        最近更新 更多