Spring中的JSR 303 Bean验证

3

这是我的表单实体:

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文档,但没有找到任何可以在运行时替换我的属性名称userIdUser Id的内容。请大家帮帮我,我已经卡在这里两天了。
如果不可能,请告诉我或者如果不行,请帮我找到其他替代方案。

谢谢
Shams

3个回答

4

您可能已经解决了这个问题,但是要在JSR 303表单bean上设置错误消息,您需要按以下格式向属性文件添加条目:

<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”属性,我仍然需要为属性文件中的每个属性创建一个新条目。 - Shams

0
在同一个message.properties文件中,您只需添加以下内容:
userId=User Id
password=Password

或者您可以使用单独的文件来存储字段名称和验证消息代码。这样会更易读。

祝好运 :)


0

为了参考,只需记录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文档以了解其他错误代码的格式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接