2016年4月1日 星期五

Filter (Servlet 八)

※Web.xml設定

<context-param>
    <param-name>abc</param-name>
    <param-value>111</param-value>
</context-param>
<context-param>
    <param-name>def</param-name>
    <param-value>222</param-value>
</context-param>
    
<filter>
    <filter-name>zzz</filter-name>
    <filter-class>filter.HelloFilter</filter-class>
    <init-param>
        <param-name>ghi</param-name>
        <param-value>333</param-value>
    </init-param>
    <init-param>
        <param-name>jkl</param-name>
        <param-value>444</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>zzz</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
    
<servlet>
    <servlet-name>ooo</servlet-name>
    <servlet-class>controller.TestServletConfig</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ooo</servlet-name>
    <url-pattern>/xxx</url-pattern>
</servlet-mapping>



public class HelloFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println(config.getInitParameter("abc"));
        System.out.println(config.getInitParameter("ghi"));
        System.out.println("init方法!");
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("doFilter方法前!");
        // chain.doFilter(req, resp);
        // System.out.println("doFilter方法後!");
    }
    
    @Override
    public void destroy() {
        System.out.println("destroy方法!");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

※abc是null,因為filter比較快

※註解的doFilter不寫會看不到頁面,因為它沒把棒子傳給下一位,沒給就表示自己是終點,頁面上就會一片空白,而之後的程式碼也會執行



※Annotation設定

@WebFilter(
    urlPatterns = "/*", 
    initParams = { 
        @WebInitParam(name = "ghi", value = "333"),
        @WebInitParam(name = "jkl", value = "444")
    }
)
public class HelloFilter implements Filter {
    // ...
}


※過濾器和攔截器的區別

1.攔截器使用反射;過濾器使用回調
2.攔截器不依賴 Servlet 容器;過濾器會依賴
3.攔截器只針對 request 請求;過濾器都可以
4.攔截器可多次調用;過濾器只在容器初始化時被調用

沒有留言:

張貼留言