views:

183

answers:

3

Is there any way to make a filtermapping not include subdirectories?

For example.

I have .xhtml files in my context root, and I also have a subfolder named "test" with files with the same extension. Is there any may to map a filter to the files in context root and not to the files in the "test" directory?

A: 

Some containers (like resin) define an extension to filter mapping definition in web.xml which allows specifying url-regexp which allows matching the urls based on regular expression. (reference). See if your container has something like this.

Gopi
+1  A: 

Using what is available for standard servlets/filters, there is no direct way to exclude the subdirectory, since *.ext style mappings include subdirectories. You could work around this by declaring another filter that specifically handles the /test/*.xhtml mapping and handles that accordingly.

mdma
But a filter with mapping /* would still include everything under /test would it not?
Stefan
That's correct. I was thinking that the first one matched is the one used, but that's not the case. Instead, you could add a url regex check in your filter - if it matches the regex, then the filter performs it's work before delegating to the remaning filter chain. If the regex doesn't match it just delegates to the filter chain without doing any work.
mdma
+2  A: 

The url-pattern is indeed restrictive in matching. It only allows exact, prefix or suffix matchnig. Not midst/overall/regex matching. So e.g. /*.xhtml what you intend to do ain't going to work.

If you want to exclude XHTML in the /test folder only, then your best is really a Filter listening on an url-pattern of *.xhtml which does basically the following job in doFilter() method:

// First cast ServletRequest to HttpServletRequest.
HttpServletRequest hsr = (HttpServletRequest) request;

// Check if requested resource is not in /test folder.
if (!hsr.getServletPath().startsWith("/test/")) {
    // Not in /test folder. Do your thing here.
}

The HttpServletRequest#getServletPath() basically returns the part of the request URI from the context path on.

You can if necessary configure the value /test as an <init-param> of the filter so that you can control the value from inside the web.xml instead of in the Filter's code.

BalusC
I first thought hard coded in Filter? but the init-param is smart. Have learnt something here.
JoseK
@Jose: you're welcome.
BalusC