Spring Ldap:查找 dn,如果不存在则不抛出异常

发布于 2024-09-25 17:04:34 字数 794 浏览 6 评论 0原文

在 Spring LDAP 中使用 LdapTemplate ,我有这段代码:

Object object=null;
try{
    String dn = "cn=readers,ou=groups,dc=mycompany, dc=com";
    object = this.ldapTemplate.lookup(dn);
} catch(final NameNotFoundException e){
    // create Object
}

但是自从我读过我的 Joshua Bloch 以来,我知道异常不应该用于控制流。有没有办法查找 dn 来查看它是否存在,而不在不存在时抛出异常?应该有,但是我找不到。我正在寻找像这样(或类似)工作的代码:

String dn = "cn=readers,ou=groups,dc=mycompany, dc=com";
Object object=this.ldapTemplate.someMethod(dn);
if(object==null){
    // create Object
}

有人可以帮忙吗?

顺便说一句:仅仅查看 JavaDoc 是没有帮助的。 JavaDocs 中没有一个抛出 NameNotFoundException 的方法是这样说的。

Using LdapTemplate in Spring LDAP, I have this code:

Object object=null;
try{
    String dn = "cn=readers,ou=groups,dc=mycompany, dc=com";
    object = this.ldapTemplate.lookup(dn);
} catch(final NameNotFoundException e){
    // create Object
}

But since I've read my Joshua Bloch I know that exceptions should not be used for control flow. Is there a way to look up a dn to see if it exists without throwing an exception if it doesn't? There must be, but I can't find it. I'm looking for code that works like this (or similar):

String dn = "cn=readers,ou=groups,dc=mycompany, dc=com";
Object object=this.ldapTemplate.someMethod(dn);
if(object==null){
    // create Object
}

Can anybody help?

BTW: just looking at the JavaDoc won't help. None of the methods that throw NameNotFoundException say so in the JavaDocs.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

命硬 2024-10-02 17:04:34

仅当您确定 DN 存在时才应使用 lookup() 方法。这通常是因为您之前搜索并找到了用户或组,并缓存了从服务器返回的 DN。

如果您正在寻找可能存在或不存在的内容,则正确使用的 API 是 ldapTemplate.search(),并带有适当的过滤器。这会返回一个结果列表,如果没有找到结果,它会返回一个空列表而不是抛出异常。

The lookup() method is only supposed to be used when you know for certain that the DN exists. This is normally because you've searched for and found a user or group previously, and cached the DN returned from the server.

If you're looking for something that might or might not be there, the right API to use is ldapTemplate.search(), with an appropriate filter. This returns a list of results, and in the case where no results are found it returns an empty list rather than throwing an exception.

淡莣 2024-10-02 17:04:34

实际上,Spring 强制您使用异常来进行流量控制(即这不是您的错,而是他们的决定)。

几个月前我使用 LdapTemplate,但我找不到更好的方法来捕获该异常并将该情况评估为“找不到用户”。

Actually, Spring force you here to use exceptions for flow control (i.e. it's not your fault, it's their decision).

I worked with LdapTemplate few months ago and I couldn't find anything better then catch that exception and evaluate that situation as "User not found".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文