Get configured url patterns in a Java Filter

1.7k Views Asked by At

I cannot find a way to get the url-mapping information inside a filter.

For instance, web.xml:

<filter>
    <filter-name>someFilter</filter-name>
    <filter-class>com.xxx.filter.SomeFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>someFilter</filter-name>
    <url-pattern>/ws/*</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>someFilter</filter-name>
    <url-pattern>/rest/*</url-pattern>
</filter-mapping>

Then inside SomeFilter I would like to get a list of the mappings ["/ws/","/rest/"]. Is there a way to get it?

@Override 
public void init(FilterConfig filterConfig){
    filterConfig.getXXX() // -> ["/ws/*","/rest/*"]???
}
2

There are 2 best solutions below

0
On

Filterconfig is per filter and is aware only of that filter. Not sure of the intention but for reading the URLs you can simply read the web.xml and search for filter URL patterns using file reading approaches

2
On

It's not perfect, but try to define them as init param inside filter, then read init-param from code

<filter>
    <filter-name>someFilter</filter-name>
    <filter-class>com.xxx.filter.SomeFilter</filter-class>
<init-param>
      <param-name>someFilter</param-name>
      <param-value>/ws/*</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>someFilter</filter-name>
    <url-pattern>/ws/*</url-pattern>
</filter-mapping>

Filter Class:

FilterConfig config;  

public void init(FilterConfig config) throws ServletException {  
    this.config=config;  
}

public void doFilter(ServletRequest req, ServletResponse resp,  
    FilterChain chain) throws IOException, ServletException {
 String s=config.getInitParameter("someFilter");
}

Try to apply that for each filter then store all values in other variable in application, but if you used one Filter in application this will help you.