如何在@春季验证唯一的用户名? [英] How to @Validate unique username in spring?

查看:99
本文介绍了如何在@春季验证唯一的用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个表单,可以提交用户名(@NaturalId)密码用户。



我想为用户添加一个唯一的用户名。我如何使用 @Valid 批注来验证此约束?如果用户名不是唯一的,我如何通过< form:error /> 在jsp中显示这些信息?

解决方案

AFAIK没有注释来做到这一点。你有两个选择:

一,创建一个自定义验证器注释。 这里是一个很好的例。打电话给你的DAO类,并检查验证器实现中的可用性。

  public boolean isValid(String object,ConstraintValidatorContext constraintContext){ 

返回userDAO.userNameAvailable(object); //检查用户名可用性的一些方法
}



在您的实体类的属性中设置unique = true。

  @Column(unique = true)
private String userName;

但这不适用于@valid,而是在持久性上引发异常。你必须使用适当的逻辑来处理这个问题。



第一个解决方案不是简单的证明。查看



第二个将永远不会失败。

更新



NimChimpsky评论说,一起使用将是一个具体的解决方案。


Let's assume that I have a form where I might submit username(@NaturalId) and password for a new user.

I would like to add the user with a unique username. How can I use @Valid annotations to validate this constraint? And if username is not unique how can I display this information in jsp via <form:error/>?

解决方案

AFAIK there isn't an annotation to do this. You have two options

One, create a custom validator annotation. Here is a very good example. Make a call to your DAO class and check the availability in the validator implementation

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

    return userDAO.userNameAvailable(object); //some method to check username availability
    }

OR

Set unique = true on your property in your entity class.

    @Column(unique = true)
    private String userName;

But this will not work with @valid, instead throw an exception on persistence. You have to use an appropriate logic to handle that.

The first solution isn't fool proof. Check this answer on SO.

The second will will never fail.

UPDATE

As NimChimpsky commented, using both together will be a concrete solution.

这篇关于如何在@春季验证唯一的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆