简体   繁体   English

Servlet过滤器 - 不要将过滤器应用于特定的过滤器

[英]Servlet Filter - Dont apply filter to a specific one

I have a web-application with login screen backed up by an Authentication Filter. 我有一个由身份验证过滤器备份的登录屏幕的Web应用程序。

I have the following in my web.xml 我的web.xml中有以下内容

<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <display-name>AuthenticationFilter</display-name>
    <filter-class>com.mycompany.secutity.AuthenticationFilter</filter-class>
</filter>

And I have the following mapping - 我有以下映射 -

<filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

But now I want to add an exception where for a specific servlet /web/MyNewServlet , I want to bypass the authenctication filter. 但是现在我想添加一个异常,对于特定的servlet /web/MyNewServlet ,我想绕过authenctication过滤器。 How can we do this? 我们应该怎么做?

There are two ways in which you could do this: 有两种方法可以做到这一点:

  • Remap the /* pattern to another pattern like /subdir/* , and thereby avoid the AuthenticationFilter from being applied against /web/MyNewServlet . /*模式重新映射到另一个模式,如/subdir/* ,从而避免将AuthenticationFilter应用于/web/MyNewServlet This is a cumbersome process as you might have several URLs in your web-application that now need to be remapped. 这是一个繁琐的过程,因为您的Web应用程序中可能有多个URL现在需要重新映射。 I would suggest doing this early in your development, or when you do not have too many URLs to remap. 我建议你在开发的早期做这件事,或者你没有太多的网址来重新映射。
  • Include an exclusion rule programatically inside your Filter implementation. 在Filter实现中以编程方式包含排除规则。 You will need to use HttpServletRequest.getServletPath and similar methods to verify if the URL fragment contains /web/MyNewServlet , and then chain the filter to the next filter or the servlet, instead of executing the body of the filter. 您将需要使用HttpServletRequest.getServletPath和类似的方法来验证URL片段是否包含/web/MyNewServlet ,然后将过滤器链接到下一个过滤器或servlet,而不是执行过滤器的主体。

Extending Vineet's idea slightly, you could add another filter, called something like DoesNotNeedAuthenticationFilter, which runs before the AuthenticationFilter, and just sets an attribute DOES_NOT_NEED_AUTHENTICATION on the request. 稍微扩展Vineet的想法,您可以添加另一个过滤器,称为DoesNotNeedAuthenticationFilter,它在AuthenticationFilter之前运行,并且只在请求上设置属性DOES_NOT_NEED_AUTHENTICATION。 The AuthenticationFilter can then check for that attribute, and pass any requests which have it. 然后,AuthenticationFilter可以检查该属性,并传递拥有该属性的任何请求。 You can then use the normal filter mapping mechanism to apply the DoesNotNeedAuthenticationFilter to the appropriate URLs or servlets. 然后,您可以使用常规筛选器映射机制将DoesNotNeedAuthenticationFilter应用于相应的URL或servlet。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM