web.xml配置五個有用的過濾器

web.xml配置五個有用的過濾器

轉載自:http://royzhou1985.iteye.com/blog/418318

一、使瀏覽器不緩存頁面的過濾器   

Java代碼 
Java代碼  收藏代碼
  1. import javax.servlet.*;        
  2. import javax.servlet.http.HttpServletResponse;        
  3. import java.io.IOException;        
  4.        
  5. /**   
  6. * 用於的使 Browser 不緩存頁面的過濾器   
  7. */       
  8. public class ForceNoCacheFilter implements Filter {         
  9.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException  {        
  10.         ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");        
  11.         ((HttpServletResponse) response).setHeader("Pragma","no-cache");        
  12.         ((HttpServletResponse) response).setDateHeader ("Expires", -1);        
  13.         filterChain.doFilter(request, response);        
  14.     }        
  15.            
  16.     public void destroy() {        
  17.     }        
  18.            
  19.     public void init(FilterConfig filterConfig) throws ServletException {        
  20.     }        
  21. }       

  
二、檢測用戶是否登陸的過濾器   
Java代碼 
Java代碼  收藏代碼
  1.     
  2. import javax.servlet.*;        
  3. import javax.servlet.http.HttpServletRequest;        
  4. import javax.servlet.http.HttpServletResponse;        
  5. import javax.servlet.http.HttpSession;        
  6. import java.util.List;        
  7. import java.util.ArrayList;        
  8. import java.util.StringTokenizer;        
  9. import java.io.IOException;        
  10.        
  11. /**   
  12. * 用於檢測用戶是否登陸的過濾器,如果未登錄,則重定向到指的登錄頁面    
  13. * 配置參數   
  14. * checkSessionKey 需檢查的在 Session 中保存的關鍵字    
  15. * redirectURL 如果用戶未登錄,則重定向到指定的頁面,URL不包括 ContextPath    
  16. * notCheckURLList 不做檢查的URL列表,以分號分開,並且 URL 中不包括 ContextPath   
  17. */       
  18. public class CheckLoginFilter implements Filter {        
  19.      protected FilterConfig filterConfig = null;        
  20.      private String redirectURL = null;        
  21.      private List notCheckURLList = new ArrayList();        
  22.      private String sessionKey = null;        
  23.        
  24.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException  {        
  25.         HttpServletRequest request = (HttpServletRequest) servletRequest;        
  26.         HttpServletResponse response = (HttpServletResponse) servletResponse;        
  27.            
  28.          HttpSession session = request.getSession();        
  29.        if(sessionKey == null)        
  30.         {        
  31.          filterChain.doFilter(request, response);        
  32.         return;        
  33.         }        
  34.        if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)        
  35.         {        
  36.          response.sendRedirect(request.getContextPath() + redirectURL);        
  37.         return;        
  38.         }        
  39.         filterChain.doFilter(servletRequest, servletResponse);        
  40.     }        
  41.        
  42.     public void destroy() {        
  43.         notCheckURLList.clear();        
  44.     }        
  45.            
  46.     private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {        
  47.         String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());        
  48.        return notCheckURLList.contains(uri);        
  49.     }        
  50.        
  51.     public void init(FilterConfig filterConfig) throws ServletException  {        
  52.         this.filterConfig = filterConfig;        
  53.         redirectURL = filterConfig.getInitParameter("redirectURL");        
  54.         sessionKey = filterConfig.getInitParameter("checkSessionKey");        
  55.            
  56.         String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");        
  57.            
  58.         if(notCheckURLListStr != null) {        
  59.             StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");        
  60.             notCheckURLList.clear();        
  61.             while(st.hasMoreTokens()) {        
  62.                 notCheckURLList.add(st.nextToken());        
  63.             }        
  64.         }        
  65.     }        
  66. }       
  

    
三、字符編碼的過濾器   
Java代碼 
Java代碼  收藏代碼
  1. import javax.servlet.*;        
  2. import java.io.IOException;        
  3.        
  4. /**   
  5. * 用於設置 HTTP 請求字符編碼的過濾器,通過過濾器參數encoding指明使用何種字符編碼,用於處理Html Form請求參數的中文問題   
  6. */       
  7. public class CharacterEncodingFilter implements Filter {        
  8.     protected FilterConfig filterConfig = null;        
  9.     protected String encoding = "";        
  10.        
  11.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {        
  12.         if(encoding != null)        
  13.             servletRequest.setCharacterEncoding(encoding);        
  14.         filterChain.doFilter(servletRequest, servletResponse);        
  15.     }        
  16.            
  17.     public void destroy() {        
  18.         filterConfig = null;        
  19.         encoding = null;        
  20.     }        
  21.            
  22.     public void init(FilterConfig filterConfig) throws ServletException {        
  23.         this.filterConfig = filterConfig;        
  24.         this.encoding = filterConfig.getInitParameter("encoding");        
  25.     }        
  26. }       


四、資源保護過濾器   
  
  Java代碼 
Java代碼  收藏代碼
  1. package catalog.view.util;        
  2.        
  3. import javax.servlet.Filter;        
  4. import javax.servlet.FilterConfig;        
  5. import javax.servlet.ServletRequest;        
  6. import javax.servlet.ServletResponse;        
  7. import javax.servlet.FilterChain;        
  8. import javax.servlet.ServletException;        
  9. import javax.servlet.http.HttpServletRequest;        
  10. import java.io.IOException;        
  11. import java.util.Iterator;        
  12. import java.util.Set;        
  13. import java.util.HashSet;           
  14. import org.apache.commons.logging.Log;        
  15. import org.apache.commons.logging.LogFactory;        
  16.        
  17. /**   
  18. * This Filter class handle the security of the application.   
  19. *   
  20. * It should be configured inside the web.xml.   
  21. *   
  22. * @author Derek Y. Shen   
  23. */       
  24. public class SecurityFilter implements Filter {        
  25.     //the login page uri        
  26.     private static final String LOGIN_PAGE_URI = "login.jsf";        
  27.        
  28.     //the logger object        
  29.     private Log logger = LogFactory.getLog(this.getClass());        
  30.        
  31.     //a set of restricted resources        
  32.     private Set restrictedResources;        
  33.        
  34.     /**   
  35.     * Initializes the Filter.   
  36.     */       
  37.     public void init(FilterConfig filterConfig) throws ServletException {        
  38.       this.restrictedResources = new HashSet();        
  39.       this.restrictedResources.add("/createProduct.jsf");        
  40.       this.restrictedResources.add("/editProduct.jsf");        
  41.       this.restrictedResources.add("/productList.jsf");        
  42.     }        
  43.        
  44.     /**   
  45.     * Standard doFilter object.   
  46.     */       
  47.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)        
  48.        throws IOException, ServletException {        
  49.         this.logger.debug("doFilter");        
  50.               
  51.         String contextPath = ((HttpServletRequest)req).getContextPath();        
  52.         String requestUri = ((HttpServletRequest)req).getRequestURI();        
  53.               
  54.         this.logger.debug("contextPath = " + contextPath);        
  55.         this.logger.debug("requestUri = " + requestUri);        
  56.               
  57.         if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {        
  58.             this.logger.debug("authorization failed");        
  59.             ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);        
  60.         } else {        
  61.             this.logger.debug("authorization succeeded");        
  62.             chain.doFilter(req, res);        
  63.         }        
  64.     }        
  65.            
  66.     public void destroy() {}        
  67.            
  68.     private boolean contains(String value, String contextPath) {        
  69.         Iterator ite = this.restrictedResources.iterator();        
  70.               
  71.         while (ite.hasNext()) {        
  72.             String restrictedResource = (String)ite.next();                    
  73.             if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {        
  74.                 return true;        
  75.             }        
  76.         }        
  77.               
  78.         return false;        
  79.     }        
  80.            
  81.     private boolean authorize(HttpServletRequest req) {        
  82.            
  83.         //處理用戶登錄        
  84.         UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);    
  85.         if (user != null && user.getLoggedIn()) {    
  86.             //user logged in    
  87.             return true;    
  88.         } else {    
  89.             return false;    
  90.         }  
  91.     }        
  92. }      


五 利用Filter限制用戶瀏覽權限 
Java代碼 
在一個系統中通常有多個權限的用戶。不同權限用戶的可以瀏覽不同的頁面。使用Filter進行判斷不僅省下了代碼量,而且如果要更改的話只需要在Filter文件裏動下就可以。   
以下是Filter文件代碼:   
  
Java代碼  收藏代碼
  1.     
  2. import java.io.IOException;          
  3. import javax.servlet.Filter;        
  4. import javax.servlet.FilterChain;        
  5. import javax.servlet.FilterConfig;        
  6. import javax.servlet.ServletException;        
  7. import javax.servlet.ServletRequest;        
  8. import javax.servlet.ServletResponse;        
  9. import javax.servlet.http.HttpServletRequest;        
  10.        
  11. public class RightFilter implements Filter {        
  12.        
  13.     public void destroy() {        
  14.     }        
  15.        
  16.     public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException, ServletException {        
  17.         // 獲取uri地址        
  18.         HttpServletRequest request=(HttpServletRequest)sreq;        
  19.         String uri = request.getRequestURI();        
  20.         String ctx=request.getContextPath();        
  21.         uri = uri.substring(ctx.length());        
  22.         //判斷admin級別網頁的瀏覽權限        
  23.         if(uri.startsWith("/admin")) {        
  24.             if(request.getSession().getAttribute("admin")==null) {        
  25.                 request.setAttribute("message","您沒有這個權限");        
  26.                 request.getRequestDispatcher("/login.jsp").forward(sreq,sres);        
  27.                 return;        
  28.             }        
  29.          }        
  30.         //判斷manage級別網頁的瀏覽權限        
  31.         if(uri.startsWith("/manage")) {            
  32.         }        
  33.         //下面還可以添加其他的用戶權限,省去。        
  34.        
  35.      }        
  36.        
  37.      public void init(FilterConfig arg0) throws ServletException {            
  38.      }        
  39.        
  40. }    



Xml代碼 
<!-- 判斷頁面的訪問權限 -->     
  <filter>     
     <filter-name>RightFilter</filter-name>     
      <filter-class>cn.itkui.filter.RightFilter</filter-class>     
  </filter>     
  <filter-mapping>     
      <filter-name>RightFilter</filter-name>     
      <url-pattern>/admin/*</url-pattern>     
  </filter-mapping>     
  <filter-mapping>     
      <filter-name>RightFilter</filter-name>     
      <url-pattern>/manage/*</url-pattern>     
  </filter-mapping>    

<!-- 判斷頁面的訪問權限 -->  
<filter>  
<filter-name>RightFilter</filter-name>  
<filter-class>cn.itkui.filter.RightFilter</filter-class>  
</filter>  
<filter-mapping>  
<filter-name>RightFilter</filter-name>  
<url-pattern>/admin/*</url-pattern>  
</filter-mapping>  
<filter-mapping>  
<filter-name>RightFilter</filter-name>  
<url-pattern>/manage/*</url-pattern>  
</filter-mapping>  

在web.xml中加入Filter的配置,如下: 
Xml代碼 
<filter>     
<filter-name>EncodingAndCacheflush</filter-name>     
<filter-class>EncodingAndCacheflush</filter-class>     
<init-param>     
<param-name>encoding</param-name>     
<param-value>UTF-8</param-value>     
</init-param>     
    </filter>     
    <filter-mapping>     
        <filter-name>EncodingAndCacheflush</filter-name>     
        <url-pattern>/*</url-pattern>     
    </filter-mapping>    
<filter>  
<filter-name>EncodingAndCacheflush</filter-name>  
<filter-class>EncodingAndCacheflush</filter-class>  
<init-param>  
<param-name>encoding</param-name>  
<param-value>UTF-8</param-value>  
</init-param>  
</filter>  
<filter-mapping>  
<filter-name>EncodingAndCacheflush</filter-name>  
<url-pattern>/*</url-pattern>  
</filter-mapping>  

要傳遞參數的時候最好使用form進行傳參,如果使用鏈接的話當中文字符的時候過濾器轉碼是不會起作用的,還有就是頁面上 

form的method也要設置爲post,不然過濾器也起不了作用。
發佈了26 篇原創文章 · 獲贊 23 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章