1. 程式人生 > >厚積薄發系列之JavaWeb的Filter

厚積薄發系列之JavaWeb的Filter

images exp nco gin end .get 是否 登陸 初始化

1.Filter的使用配置

  • 創建一個類使其實現javax.servlet.Filter接口
  • 實現接口方法 destroy() doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) init(FilterConfig arg0)
  • 配置web.xml
  •     <filter>
            <filter-name>TestFilter</filter-name>
            <filter-class>filter.TestFilter</filter-class
    > </filter> <filter-mapping> <filter-name>TestFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

2.Filter的運行流程(兩張圖來展示)

  • 技術分享
  • 技術分享

3.Filter接口的方法

  • init(FilterConfig config):初始化操作
  • doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    :處理業務邏輯
  • destroy() :銷毀操作

4.Filter的聲明周期

  • 初始化操作 在服務器啟動的時候 根據web.xml配置文件創建Filter實例 調用init方法 實現初始化操作
  • 處理業務邏輯 在用戶的一次請求 創建一個新的線程 根據路徑調用相應的過濾器的doFilter執行業務邏輯
  • 結束階段 當Filter被移除的時候或者服務器正常關閉的時候 調用destory方法 銷毀該實例
  • 註意Filter是單實例多線程的

5.Filter的常見用法

  • post和get請求統一utf-8編碼 web.xml路徑配置為/*
  • 技術分享
      1 import java.io.IOException;
    
    2 import java.io.UnsupportedEncodingException; 3 import java.util.Map; 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.HttpServletRequestWrapper; 13 import javax.servlet.http.HttpServletResponse; 14 /** 15 * 統一編碼 16 * @author Administrator 17 * 18 */ 19 public class EncodingFilter implements Filter { 20 21 @Override 22 public void init(FilterConfig filterConfig) throws ServletException { 23 // TODO Auto-generated method stub 24 25 } 26 27 @Override 28 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { 29 //1.強轉 30 HttpServletRequest request=(HttpServletRequest) req; 31 HttpServletResponse response=(HttpServletResponse) resp; 32 33 //2.放行 34 chain.doFilter(new MyRequest(request), response); 35 } 36 37 @Override 38 public void destroy() { 39 // TODO Auto-generated method stub 40 41 } 42 43 } 44 class MyRequest extends HttpServletRequestWrapper{ 45 private HttpServletRequest request; 46 private boolean flag=true; 47 48 49 public MyRequest(HttpServletRequest request) { 50 super(request); 51 this.request=request; 52 } 53 54 @Override 55 public String getParameter(String name) { 56 if(name==null || name.trim().length()==0){ 57 return null; 58 } 59 String[] values = getParameterValues(name); 60 if(values==null || values.length==0){ 61 return null; 62 } 63 64 return values[0]; 65 } 66 67 @Override 68 /** 69 * hobby=[eat,drink] 70 */ 71 public String[] getParameterValues(String name) { 72 if(name==null || name.trim().length()==0){ 73 return null; 74 } 75 Map<String, String[]> map = getParameterMap(); 76 if(map==null || map.size()==0){ 77 return null; 78 } 79 80 return map.get(name); 81 } 82 83 @Override 84 /** 85 * map{ username=[tom],password=[123],hobby=[eat,drink]} 86 */ 87 public Map<String,String[]> getParameterMap() { 88 89 /** 90 * 首先判斷請求方式 91 * 若為post request.setchar...(utf-8) 92 * 若為get 將map中的值遍歷編碼就可以了 93 */ 94 String method = request.getMethod(); 95 if("post".equalsIgnoreCase(method)){ 96 try { 97 request.setCharacterEncoding("utf-8"); 98 return request.getParameterMap(); 99 } catch (UnsupportedEncodingException e) { 100 // TODO Auto-generated catch block 101 e.printStackTrace(); 102 } 103 }else if("get".equalsIgnoreCase(method)){ 104 Map<String,String[]> map = request.getParameterMap(); 105 if(flag){ 106 for (String key:map.keySet()) { 107 String[] arr = map.get(key); 108 //繼續遍歷數組 109 for(int i=0;i<arr.length;i++){ 110 //編碼 111 try { 112 arr[i]=new String(arr[i].getBytes("iso8859-1"),"utf-8"); 113 } catch (UnsupportedEncodingException e) { 114 e.printStackTrace(); 115 } 116 } 117 } 118 flag=false; 119 } 120 //需要遍歷map 修改value的每一個數據的編碼 121 122 return map; 123 } 124 125 return super.getParameterMap(); 126 } 127 128 }
    View Code

  • 登陸驗證 判斷用戶是否登陸 web.xml路徑配置自己想要用戶登陸才能登陸登陸才能訪問的頁面
  • 技術分享
     1 public void doFilter(ServletRequest arg0, ServletResponse arg1,
     2             FilterChain arg2) throws IOException, ServletException {
     3         
     4         HttpServletRequest request=(HttpServletRequest) arg0;
     5         HttpServletResponse response=(HttpServletResponse) arg1;
     6         HttpSession session=request.getSession();
     7         
     8         String path=request.getRequestURI();
     9         
    10         Integer uid=(Integer)session.getAttribute("userid");
    11         
    12         if(path.indexOf("/login.jsp")>-1){//登錄頁面不過濾
    13             arg2.doFilter(arg0, arg1);//遞交給下一個過濾器
    14             return;
    15         }
    16         if(path.indexOf("/register.jsp")>-1){//註冊頁面不過濾
    17             arg2.doFilter(request, response);
    18             return;
    19         }
    20         
    21         if(uid!=null){//已經登錄
    22             arg2.doFilter(request, response);//放行,遞交給下一個過濾器
    23             
    24         }else{
    25             response.sendRedirect("login.jsp");
    26         }
    27 
    28     }
    View Code

  • 禁止瀏覽器緩存動態頁面 web.xml路徑配置為不想讓瀏覽器緩存的頁面
  • 技術分享
     1  @Override
     2     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     3             throws IOException, ServletException {
     4 
     5         HttpServletRequest request = (HttpServletRequest) req;
     6         HttpServletResponse response = (HttpServletResponse) resp;
     7 
     8         response.setDateHeader("Expires",-1);
     9         response.setHeader("Cache-Control","no-cache");
    10         response.setHeader("Pragma","no-cache");
    11 
    12         chain.doFilter(request, response);
    13 
    14     }
    15 
    16     @Override
    View Code

厚積薄發系列之JavaWeb的Filter