歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java Web之Filter

Filter被稱為過濾器或者攔截器,基本功能就是對調用servler過程的攔截,在servlet進行響應和處理前後實現一些特殊功能。其實,Filter過濾器就是一個實現了javax.servlet.Filter接口的類,在javax.servlet.Filter接口中定義了3個方法:

  • init(FilterConfig filterConfig) : 用來初始化過濾器,可以在init()中完成與構造方法類似的初始化功能,如果初始化代碼中要使用FilterConfig對象,那麼,這些初始化代碼就只能在Filter的init()方法中編寫,而不能在構造方法中編寫。
  • doFilter(ServletRequest request, ServletResponse response, FilterChain chain) : request和response為Web服務器或Filter鏈中的上一個Filter對象傳遞過來的請求和響應對象;參數chain代表Filter鏈的對象,在當前Filter對象中的doFilter()方法內需要調用FilterChain對象的doFilter()方法,才能把請求交付給Filter鏈的下一個Filter或者目標程序去處理。
  • public void destroy() : destroy()方法在Web服務器卸載Filter之前被調用,該方法用於釋放Filter對象打開的資源,例如關閉數據庫和IO流。

1、實現第一個Filter程序

Index.java文件如下:

package com.net;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Index extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("Index");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

MyFilter.java文件如下

package com.net;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilter implements Filter {
    public void init(FilterConfig fConfig) throws ServletException {
        System.out.println("MyFilter.init()");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        PrintWriter out = response.getWriter();
        out.println("Hello MyFilter");
        chain.doFilter(request, response);
    }
   
    public void destroy() {
        System.out.println("MyFilter.destroy()");
    }
}

web.xml配置文件添加如下代碼:

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.net.MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/Index</url-pattern>
</filter-mapping>


<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>com.net.Index</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/Index</url-pattern>
</servlet-mapping>

測試結果如下:

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2016-04/129790p2.htm

Copyright © Linux教程網 All Rights Reserved