正如其他人所指出的,没有办法仅使用基本的 servlet 过滤器功能来使用正则表达式匹配进行过滤。servlet规范的编写方式可能是为了允许URL的有效匹配,并且因为servlet早于java中正则表达式的可用性(正则表达式到达java 1.4)。
正则表达式的性能可能会降低(不,我还没有对其进行基准测试),但是如果您不受处理时间的严格限制,并希望牺牲性能以方便配置,则可以这样做:
在过滤器中:
private String subPathFilter = ".*";
private Pattern pattern;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String subPathFilter = filterConfig.getInitParameter("subPathFilter");
if (subPathFilter != null) {
this.subPathFilter = subPathFilter;
}
pattern = Pattern.compile(this.subPathFilter);
}
public static String getFullURL(HttpServletRequest request) {
// Implement this if you want to match query parameters, otherwise
// servletRequest.getRequestURI() or servletRequest.getRequestURL
// should be good enough. Also you may want to handle URL decoding here.
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
Matcher m = pattern.matcher(getFullURL((HttpServletRequest) servletRequest));
if (m.matches()) {
// filter stuff here.
}
}
然后在网络中.xml...
<filter>
<filter-name>MyFiltersName</filter-name>
<filter-class>com.example.servlet.MyFilter</filter-class>
<init-param>
<param-name>subPathFilter</param-name>
<param-value>/org/test/[^/]+/keys/.*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFiltersName</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
有时,通过反转 if 语句来使模式排除匹配项也很方便(或者为排除模式添加另一个 init 参数,这留给读者作为练习。doFilter()