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代码 
     
       
     RightFilter     
      cn.itkui.filter.RightFilter     
       
       
      RightFilter     
      /admin/*     
       
       
      RightFilter     
      /manage/*     
      

  
  
RightFilter  
cn.itkui.filter.RightFilter  
  
  
RightFilter  
/admin/*  
  
  
RightFilter  
/manage/*  
  

在web.xml中加入Filter的配置,如下: 
Xml代码 
     
EncodingAndCacheflush     
EncodingAndCacheflush     
     
encoding     
UTF-8     
     
         
         
        EncodingAndCacheflush     
        /*     
        
  
EncodingAndCacheflush  
EncodingAndCacheflush  
  
encoding  
UTF-8  
  
  
  
EncodingAndCacheflush  
/*  
  

要传递参数的时候最好使用form进行传参,如果使用链接的话当中文字符的时候过滤器转码是不会起作用的,还有就是页面上 

form的method也要设置为post,不然过滤器也起不了作用。

你可能感兴趣的:(java)