Reputation: 13
When does a Java Filter start? Does the Filter init()
method overide the servlet init()
method? Where do I declare the init parameters in web.xml
?
Upvotes: 1
Views: 478
Reputation: 1109635
When does a Java Filter start?
During startup of the webapplication.
Does the Filter
init()
method overide the servletinit()
method?
No. They are in no way related to each other. The init()
method of your filter just implements the one as definied in javax.servlet.Filter
interface.
Where do I declare the init parameters in
web.xml
?
Inside the <filter>
declaration.
<filter>
<filter-name>myFilter</filter-name>
<filter-class>com.example.MyFilter</filter-class>
<init-param>
<param-name>foo</param-name>
<param-value>bar</param-value>
</init-param>
</filter>
It'll then be available inside init()
as follows:
@Override
public void init(FilterConfig config) {
String foo = config.getInitParameter("foo"); // contains "bar".
}
Upvotes: 3
Reputation: 116306
Declare it in web.xml like
<web-app version=...>
...
<filter>
<description>...</description>
<display-name>My Filter</display-name>
<filter-name>MyFilter</filter-name>
<filter-class>com.foo.bar.MyFilter</filter-class>
</filter>
...
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/some/path</url-pattern>
</filter-mapping>
...
</web-app>
[Update] The <filter>
section registers your filter to the system; it will be automatically started up when the web app is started. In the <filter-mapping>
section you can configure when (on what URLs) to invoke your filter. [/Update]
The rest of your questions is already answered by @BalusC.
Upvotes: 1