編寫Filter的時候,我們需要實現Filter接口,需要去實現init(FilterConfig arg0),doFilter(ServletRequest request, ServletResponse response, FilterChain chain),destroy()等方法,有時候我們並不需要去實現init與destory方法,但又必須在代碼裡面寫上這兩個方法.如果我們不想多寫這個兩個方法,我們可以用一個類去實現Filter接口,在我們開發的時候直接繼承這個類,實現doFilter方法即可.
代碼如下:
1 package com.zhx.http.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 /** 15 * 16 * @author zhaoxin 17 * 自定義的HttpFilter,實現Filter接口,參考自GenericServlet的實現方式 18 */ 19 public abstract class HttpFilter implements Filter,java.io.Serializable { 20 21 private static final long serialVersionUID = 1L; 22 23 private FilterConfig filterConfig; 24 25 /** 26 * 該方法由servlet容器進行調用,有且只調用一次 27 * 不建議子類直接重寫該方法 28 */ 29 @Override 30 public void init(FilterConfig arg0) throws ServletException { 31 this.filterConfig = arg0; 32 this.init(); 33 } 34 35 /** 36 * 供子類重寫的初始化方法,在子類中可以在init()方法中調用getFilterConfig()方法來獲取FilterConfig對象,來獲取初始化參數 37 * @throws ServletException 38 */ 39 protected void init() throws ServletException { 40 //TODO Auto-generated method stub 41 } 42 43 /** 44 * 供子類調用,來獲取FilterConfig對象 45 * @return 46 */ 47 public FilterConfig getFilterConfig() { 48 return filterConfig; 49 } 50 51 /** 52 * 該方法由servlet容器調用,不建議之類直接進行重寫 53 */ 54 @Override 55 public void doFilter(ServletRequest req, ServletResponse res, 56 FilterChain fc) throws IOException, ServletException { 57 58 HttpServletRequest request; 59 HttpServletResponse response; 60 61 try { 62 request = (HttpServletRequest)req; 63 response = (HttpServletResponse)res; 64 } catch (Exception e) { 65 throw new ServletException("non-HTTP request or response"); 66 } 67 doFilter(request, response, fc); 68 } 69 70 /** 71 * 該方法由子類必須重寫的過濾方法 72 * @param request 73 * @param response 74 * @param filterChain 75 * @throws IOException 76 * @throws ServletException 77 */ 78 public abstract void doFilter(HttpServletRequest request, HttpServletResponse response, 79 FilterChain filterChain) throws IOException, ServletException; 80 81 /** 82 * 由servlet容器進行調用 83 */ 84 @Override 85 public void destroy() { 86 // TODO Auto-generated method stub 87 88 } 89 90 }
開發的時候我們只需新建一個類,然後去繼承HttpFilter即可.如果有初始化的需要,建議重寫無參的init()方法,如果想在該方法內使用FilterConfig對象,通過調用this.getFilterConfig()方法即可獲得.編寫過濾方法時建議重寫doFilter(HttpServletRequest request, HttpServletResponse response,FilterChain filterChain).該方法的好處是可以直接使用HttpServletRequest,HttpServletResponse,不用自己再去將ServletRequest,ServletResponse對象強制轉換為HttpServletRequest,HttpServletResponse對象.如果有釋放資源等操作的時候,直接重寫destory()方法即可,沒有的話就不用重寫.可以讓代碼看上去更美觀.