我可以从 <url-pattern> 中排除一些具体的 url 吗?在 <filter-mapping> 里面? [英] Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?
问题描述
我希望对除一个具体之外的所有 url 应用一些具体过滤器(即对于 /*
,除了 /specialpath
).
I want some concrete filter to be applied for all urls except for one concrete (i.e. for /*
except for /specialpath
).
有没有可能做到这一点?
Is there a possibility to do that?
示例代码:
<filter>
<filter-name>SomeFilter</filter-name>
<filter-class>org.somproject.AFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SomeFilter</filter-name>
<url-pattern>/*</url-pattern> <!-- the question is: how to modify this line? -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
推荐答案
标准 Servlet API 不支持此功能.您可能希望为此使用重写 URL 过滤器,例如 Tuckey 的过滤器(这与 Apache HTTPD 的 mod_rewrite
),或者在/*
上监听Filter的doFilter()
方法中添加一个检查.
The standard Servlet API doesn't support this facility. You may want either to use a rewrite-URL filter for this like Tuckey's one (which is much similar Apache HTTPD's mod_rewrite
), or to add a check in the doFilter()
method of the Filter listening on /*
.
String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
chain.doFilter(request, response); // Just continue chain.
} else {
// Do your business stuff here for all paths other than /specialpath.
}
如有必要,您可以将要忽略的路径指定为过滤器的 init-param
,以便您无论如何都可以在 web.xml
中控制它.您可以按如下方式在过滤器中获取它:
You can if necessary specify the paths-to-be-ignored as an init-param
of the filter so that you can control it in the web.xml
anyway. You can get it in the filter as follows:
private String pathToBeIgnored;
public void init(FilterConfig config) {
pathToBeIgnored = config.getInitParameter("pathToBeIgnored");
}
如果过滤器是第 3 方 API 的一部分,因此您无法修改它,则将其映射到更具体的 url-pattern
,例如/otherfilterpath/*
并在 /*
上创建一个新的过滤器,它转发到与第 3 方过滤器匹配的路径.
If the filter is part of 3rd party API and thus you can't modify it, then map it on a more specific url-pattern
, e.g. /otherfilterpath/*
and create a new filter on /*
which forwards to the path matching the 3rd party filter.
String path = ((HttpServletRequest) request).getRequestURI();
if (path.startsWith("/specialpath/")) {
chain.doFilter(request, response); // Just continue chain.
} else {
request.getRequestDispatcher("/otherfilterpath" + path).forward(request, response);
}
为避免此过滤器在无限循环中调用自身,您需要让它仅在 REQUEST
上侦听(调度),并且仅在 FORWARD
上监听(调度)第 3 方过滤器.
To avoid that this filter will call itself in an infinite loop you need to let it listen (dispatch) on REQUEST
only and the 3rd party filter on FORWARD
only.
- 如何预防由映射到/* 的前端控制器 servlet 处理的静态资源
- 如何在 Spring 中处理静态内容MVC?
这篇关于我可以从 <url-pattern> 中排除一些具体的 url 吗?在 <filter-mapping> 里面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!