過濾器屬於Servlet規範,從2.3版本就開始有了。html
過濾器就是對訪問的內容進行篩選(攔截)。利用過濾器對請求和響應進行過濾
緩存
誕生:過濾器的實例是在應用被加載時就完成的實例化,並初始化的。 存活:和應用的生命週期一致的。在內存中是單例的。針對攔截範圍內的資源訪問,每次訪問都會調用void doFIlter(request,response.chain)進行攔截。 死亡:應用被卸載。
public class FilterDemo1 implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //對請求進行攔截,代碼寫在這裏 System.out.println("過濾前"); chain.doFilter(request, response);//放行,訪問過濾文件 //對響應進行攔截,代碼寫在這裏 System.out.println("過濾後"); } public void init(FilterConfig arg0) throws ServletException { System.out.println("初始化方法"); } public void destroy() { } }
public class SetCharacterEncodingFilter implements Filter { private FilterConfig filterConfig; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String encoding = filterConfig.getInitParameter("encoding");//用戶可能忘記了配置該參數 if(encoding==null){ encoding = "UTF-8";//默認編碼 } request.setCharacterEncoding(encoding);//只能解決(表單提交)POST請求參數的中文問題 response.setCharacterEncoding(encoding);//輸出流編碼 response.setContentType("text/html;charset="+encoding);//輸出流編碼,通知了客戶端應該使用的編碼 chain.doFilter(request, response); } public void destroy() { } }
//控制servlet,jsp不要緩存過濾器 public class NoCacheFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // HttpServletRequest request = (HttpServletRequest)req; // HttpServletResponse response = (HttpServletResponse)resp; HttpServletRequest request = null; HttpServletResponse response = null; try{ request = (HttpServletRequest)req; response = (HttpServletResponse)resp; }catch(Exception e){ throw new RuntimeException("not-http request or response"); } response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); chain.doFilter(request, response); } public void destroy() { } }