我可以从< url-pattern>中排除一些具体的网址吗?在里面< filter-mapping>? [英] Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

查看:120
本文介绍了我可以从< url-pattern>中排除一些具体的网址吗?在里面< 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).

是否有可能这样做?

示例代码:

<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 ),或者在上监听过滤器的 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.
}

您可以根据需要指定要忽略的路径<过滤器的code> 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");
}

如果过滤器是第三方API的一部分,因此您无法修改它,然后将其映射到更具体的 url-pattern ,例如 / otherfilterpath / * 并在 / * 上创建一个新过滤器,转发到与第三方过滤器匹配的路径。

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 上过滤。

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.

  • How to prevent static resources from being handled by front controller servlet which is mapped on /*
  • How to handle static content in Spring MVC?

这篇关于我可以从&lt; url-pattern&gt;中排除一些具体的网址吗?在里面&lt; filter-mapping&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆