Spring Ldap:查找 dn,如果不存在则不抛出异常
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当您确定 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.实际上,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".