3

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/*"]???
}
codependent
  • 23,193
  • 31
  • 166
  • 308
  • A question, why do you need to know the list of mappings? – Anand S Kumar Jun 25 '15 at 09:19
  • @jWeaver This question has nothing to do with the one you suggested... – codependent Jun 25 '15 at 09:38
  • 2
    **Why are all these people marking this as a dup?** The referred question is about configuring url patterns in the web.xml. This question is about reading that config in the Java code. The fact that the referred question has only XML examples and no Java code should be a pretty big hint that this question is NOT a duplicate. – Stijn de Witt Nov 24 '15 at 09:36

2 Answers2

0

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.

Safwan Hijazi
  • 2,089
  • 2
  • 17
  • 29
  • The point is that i need to know the list of url's configured in `url-pattern` – codependent Jun 25 '15 at 08:25
  • Thanks for the suggestion, I had already thought of that. However it's kind of a workaround. I am wondering if there is a standard way to achive that. – codependent Jun 25 '15 at 09:39
0

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

Mudassar
  • 3,135
  • 17
  • 22