开发者

How to use a Filter?

开发者 https://www.devze.com 2023-02-07 15:09 出处:网络
When does a Java Filter start? Does the Filter init() method overide the servlet init() method? Where do I declare the init parameters i开发者_JS百科n web.xml?

When does a Java Filter start? Does the Filter init() method overide the servlet init() method? Where do I declare the init parameters i开发者_JS百科n web.xml?


When does a Java Filter start?

During startup of the webapplication.


Does the Filter init() method overide the servlet init() 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".
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消