kasdega
kasdega

Reputation: 18776

In a web.xml url-pattern matcher is there a way to exclude URLs?

I wrote a filter that needs to be invoked every time a url on my site is accessed EXCEPT the CSS, JS, and IMAGE files. So in my definition I'd like to have something like:

<filter-mapping>
   <filter-name>myAuthorizationFilter</filter-name>
   <url-pattern>NOT /css && NOT /js && NOT /images</url-pattern>
</filter-mapping>

Is there anyway to do this? The only documentation I can find has only /*

UPDATE:

I ended up using something similar to an answer provided by Mr.J4mes:

   private static Pattern excludeUrls = Pattern.compile("^.*/(css|js|images)/.*$", Pattern.CASE_INSENSITIVE);
   private boolean isWorthyRequest(HttpServletRequest request) {
       String url = request.getRequestURI().toString();
       Matcher m = excludeUrls.matcher(url);

       return (!m.matches());
   }

Upvotes: 24

Views: 47849

Answers (4)

Wendel
Wendel

Reputation: 2977

I used the security-constraint to access control. See the code:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Unsecured resources</web-resource-name>
        <url-pattern>/resources/*</url-pattern>
        <url-pattern>/javax.faces.resource/*</url-pattern>
    </web-resource-collection>
</security-constraint>

I follow this tutorial.

Upvotes: 0

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

Probably you could declare another "blank" filter for css, js etc, and put it before others filter mapping.

Upvotes: 1

Perception
Perception

Reputation: 80593

The URL pattern mapping does not support exclusions. This is a limitation of the Servlet specification. You can try the manual workaround posted by Mr.J4mes.

Upvotes: 6

Mr.J4mes
Mr.J4mes

Reputation: 9266

I think you can try this one:

@WebFilter(filterName = "myFilter", urlPatterns = {"*.xhtml"})
public class MyFilter implements Filter {

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
      String path = ((HttpServletRequest) request).getServletPath();

      if (excludeFromFilter(path)) chain.doFilter(request, response);
      else // do something
   }

   private boolean excludeFromFilter(String path) {
      if (path.startsWith("/javax.faces.resource")) return true; // add more page to exclude here
      else return false;
   }
}

Upvotes: 21

Related Questions