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