4

I have a filter that looks like this:

   <filter>
      <filter-name>TestFilter</filter-name>
      <filter-class>org.TestFilter</filter-class>
      <init-param>
         <param-name>timeout</param-name>
         <param-value>30</param-value>
      </init-param>
   </filter>

Since we are talking ServletFilter and Servlets. Essentially, I am already in my servlet and have executed the first part of the doFilter. So the container must know the init-parameter. I don't have access to change the Filter class.

Is it possible to get the init-parameter value given an HttpServletRequest object?

The only solution I can think of is to read the web.xml as a resource and try to find the value manually. But it feels like there is a better solution.

2 Answers 2

8

Why would you need it in your servlet to begin with? Filter parameter belongs to filter. Your options are:

  1. Move said parameter to context init parameter; you'll be able to access it from both filter and servlet.
  2. In your filter's doFilter method set an attribute (on request) with parameter value, have you servlet read it.

Context parameter example.

web.xml:

  <context-param>
    <param-name>param1</param-name>
    <param-value>value</param-value>
  </context-param>

your code:

String paramValue = getServletContext().getInitParameter("param1");

and the filter would have access to the same param value using:

String paramValue = filterConfig.getServletContext().getInitParameter("param1");
2
  • ironically quite often we need filter params in HttpServletResponseWrapper instance, which has no direct access to filter itself.
    – shabunc
    Commented Feb 14, 2012 at 10:23
  • not working for me. I have code inside HttpServletResponseWrapper.
    – Arjun
    Commented May 11, 2015 at 12:35
1

If the filter is not declared final, you can extend it. For example,

public class MyFilter extends TheirFilter {
    public void init(javax.servlet.FilterConfig filterConfig) 
        throws javax.servlet.ServletException {
        super(filterConfig);
        // Retrieve the parameter here
    }
}

Then change the web.xml to change the filter class to yours.

Not the answer you're looking for? Browse other questions tagged or ask your own question.