spring 如何在春季@Validate 唯一用户名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17092601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:01:07  来源:igfitidea点击:

How to @Validate unique username in spring?

springhibernatevalidationspring-mvc

提问by user902691

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

让我们假设我有一个表格,我会提交username(@NaturalId)password为新用户。

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

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

回答by shazinltc

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

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

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

一,创建自定义验证器注释。是一个很好的例子。调用您的 DAO 类并检查验证器实现中的可用性

    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.

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

    @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.

但这不适用于@valid,而是在持久性上抛出异常。您必须使用适当的逻辑来处理它。

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

第一个解决方案不是万无一失的。在 SO 上查看答案。

The second will will never fail.

第二个永远不会失败。

UPDATE

更新

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

正如 NimChimpsky 评论的那样,将两者结合使用将是一个具体的解决方案。

回答by lunr

JSR-303 does not support what you want (something like a @Uniqueconstraint). You have to write you own validator. How can this be done is explained here: https://community.jboss.org/wiki/AccessingtheHibernateSessionwithinaConstraintValidator

JSR-303 不支持您想要的(类似于@Unique约束)。您必须编写自己的验证器。这里解释了如何做到这一点:https: //community.jboss.org/wiki/AccessingtheHibernateSessionwithinaConstraintValidator

But before doing that make sure you read this answer: https://stackoverflow.com/a/3499111/1981720

但在此之前,请确保您阅读此答案:https: //stackoverflow.com/a/3499111/1981720

And this sentence from the previous article:

还有上一篇文章中的这句话:

The reason @Unique is not part of the built-in constraints is the fact that accessing the Session/EntityManager during a valiation is opening yourself up for potenital phantom reads.

@Unique 不是内置约束的一部分的原因是,在验证期间访问 Session/EntityManager 会为潜在的幻读打开自己的大门。

回答by Pasha GR

You can use UserDetailsService prepared spring class and extend it and customize it :

您可以使用 UserDetailsS​​ervice 准备好的 spring 类并对其进行扩展和自定义:

@Service
public class LoginDetailsServiceImpl implements UserDetailsService, Serializable {

    @Autowired
    LoginService loginService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == "" || username.isEmpty()) {
            throw new UsernameNotFoundException(String.format("User %s is invalid!", username));
        }
        Login login = loginService.find(username);
        if (login == null) {
            throw new UsernameNotFoundException(String.format("User %s does not exist!", username));
        }
        if (!loginService.scheduleChecking(login.getScheduled())) {
            throw new UsernameNotFoundException(String.format("User %s is not authorized this time!", username));
        }
      //....