Filters

除了使用一组属性指定搜索外,您还可以以搜索过滤器的形式指定搜索。搜索过滤器是以逻辑表达式的形式表示的搜索查询。 DirContext.search()接受的搜索过滤器的语法在RFC 2254中描述。

以下搜索过滤器指定符合条件的条目必须具有"sn"属性的值"Geisel""mail"属性的任何值:

(&(sn=Geisel)(mail=*))

以下代码创建一个过滤器和默认的SearchControls,并使用它们执行搜索。搜索等同于basic search示例中显示的搜索。

// Create the default search controls
SearchControls ctls = new SearchControls();

// Specify the search filter to match
// Ask for objects that have the attribute "sn" == "Geisel"
// and the "mail" attribute
String filter = "(&(sn=Geisel)(mail=*))";

// Search for objects using the filter
NamingEnumeration answer = ctx.search("ou=People", filter, ctls);

运行this example会产生以下结果。

# java SearchWithFilterRetAll
>>>cn=Ted Geisel
attribute: sn
value: Geisel
attribute: objectclass
value: top
value: person
value: organizationalPerson
value: inetOrgPerson
attribute: jpegphoto
value: [B@1dacd75e
attribute: mail
value: [email protected]
attribute: facsimiletelephonenumber
value: +1 408 555 2329
attribute: cn
value: Ted Geisel
attribute: telephonenumber
value: +1 408 555 5252

搜索过滤器语法快速概述

搜索过滤器语法基本上是前缀表示法中的逻辑表达式(即,逻辑运算符出现在其参数之前)。下表列出了用于创建过滤器的符号。

SymbolDescription
&连词(即-列表中的所有字母必须为真)
|析取(即-一个或多个替代必须为真)
!否定(即* not *-被否定的项目不能为真)
=相等(根据属性的匹配规则)
~=近似相等(根据属性的匹配规则)
>=大于(根据属性的匹配规则)
<=小于(根据属性的匹配规则)
=*存在(即条目必须具有属性,但其值无关紧要)
*通配符(指示该位置可以出现零个或多个字符);在指定属性值以匹配时使用
转义(用于在属性值内出现时转义'*','('或')')

过滤器中的每个项目均使用属性标识符和属性值或表示属性值的符号组成。例如,项目"sn=Geisel"表示"sn"属性必须具有属性值"Geisel",项目"mail=\*"表示"mail"属性必须存在。

必须将每个项目括在一组括号内,如"\(sn=Geisel\)"。这些项目是使用诸如&的逻辑运算符(连词)组成的,以创建逻辑表达式,如"\(& \(sn=Geisel\) \(mail=\*\)\)"

每个逻辑表达式还可以由其他项组成,这些项本身就是逻辑表达式,如"\(\| \(& \(sn=Geisel\) \(mail=\*\)\) \(sn=L\*\)\)"。最后一个示例是请求具有"Geisel""mail"属性的"sn"属性的条目,或者请求具有"sn"属性的字母“ L”开头的条目。

有关语法的完整说明,请参见RFC 2254

返回所选属性

前面的示例返回了与满足指定过滤器的条目相关联的所有属性。您可以通过设置搜索控件参数来选择要返回的属性。您创建要包含在结果中的属性标识符数组,并将其传递给SearchControls.setReturningAttributes()。这是一个例子。

// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);

此示例等效于“基本搜索”部分中的返回选定的属性示例。运行this example会产生以下结果。 (该条目没有"golfhandicap"属性,因此不会返回.)

# java SearchWithFilter
>>>cn=Ted Geisel
attribute: sn
value: Geisel
attribute: mail
value: [email protected]
attribute: telephonenumber
value: +1 408 555 5252