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.       
  10. public   void  doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)  throws  IOException, ServletException       
  11. {       
  12.     ((HttpServletResponse) response).setHeader( "Cache-Control" , "no-cache" );       
  13.     ((HttpServletResponse) response).setHeader( "Pragma" , "no-cache" );       
  14.     ((HttpServletResponse) response).setDateHeader ( "Expires" , - 1 );       
  15.     filterChain.doFilter(request, response);       
  16. }       
  17.       
  18. public   void  destroy()       
  19. {       
  20. }       
  21.       
  22.        public   void  init(FilterConfig filterConfig)  throws  ServletException       
  23. {       
  24. }       
  25. }    

  
  
二、检测用户是否登陆的过滤器    

  1. import  javax.servlet.*;       
  2. import  javax.servlet.http.HttpServletRequest;       
  3. import  javax.servlet.http.HttpServletResponse;       
  4. import  javax.servlet.http.HttpSession;       
  5. import  java.util.List;       
  6. import  java.util.ArrayList;       
  7. import  java.util.StringTokenizer;       
  8. import  java.io.IOException;       
  9.       
  10. /**     
  11. * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面      
  12.     
  13.     
  14. * 配置参数      
  15.     
  16.     
  17. * checkSessionKey 需检查的在 Session 中保存的关键字     
  18.     
  19. * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath     
  20.     
  21. * notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath     
  22.     
  23. */       
  24. public   class  CheckLoginFilter       
  25. implements  Filter       
  26. {       
  27.        protected  FilterConfig filterConfig =  null ;       
  28.        private  String redirectURL =  null ;       
  29.        private  List notCheckURLList =  new  ArrayList();       
  30.        private  String sessionKey =  null ;       
  31.       
  32. public   void  doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)  throws  IOException, ServletException       
  33. {       
  34.     HttpServletRequest request = (HttpServletRequest) servletRequest;       
  35.     HttpServletResponse response = (HttpServletResponse) servletResponse;       
  36.       
  37.      HttpSession session = request.getSession();       
  38.      if (sessionKey ==  null )       
  39.     {       
  40.      filterChain.doFilter(request, response);       
  41.       return ;       
  42.     }       
  43.      if ((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) ==  null )       
  44.     {       
  45.      response.sendRedirect(request.getContextPath() + redirectURL);       
  46.       return ;       
  47.     }       
  48.     filterChain.doFilter(servletRequest, servletResponse);       
  49. }       
  50.       
  51. public   void  destroy()       
  52. {       
  53.     notCheckURLList.clear();       
  54. }       
  55.       
  56. private   boolean  checkRequestURIIntNotFilterList(HttpServletRequest request)       
  57. {       
  58.     String uri = request.getServletPath() + (request.getPathInfo() ==  null  ?  ""  : request.getPathInfo());       
  59.      return  notCheckURLList.contains(uri);       
  60. }       
  61.       
  62. public   void  init(FilterConfig filterConfig)  throws  ServletException       
  63. {       
  64.      this .filterConfig = filterConfig;       
  65.     redirectURL = filterConfig.getInitParameter( "redirectURL" );       
  66.     sessionKey = filterConfig.getInitParameter( "checkSessionKey" );       
  67.       
  68.     String notCheckURLListStr = filterConfig.getInitParameter( "notCheckURLList" );       
  69.       
  70.      if (notCheckURLListStr !=  null )       
  71.     {       
  72.      StringTokenizer st =  new  StringTokenizer(notCheckURLListStr,  ";" );       
  73.      notCheckURLList.clear();       
  74.       while (st.hasMoreTokens())       
  75.      {       
  76.       notCheckURLList.add(st.nextToken());       
  77.      }       
  78.     }       
  79. }       
  80. }      


  
三、字符编码的过滤器    

  1. import  javax.servlet.*;       
  2. import  java.io.IOException;       
  3.       
  4. /**     
  5. * 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题     
  6. */       
  7. public   class  CharacterEncodingFilter       
  8. implements  Filter       
  9. {       
  10. protected  FilterConfig filterConfig =  null ;       
  11. protected  String encoding =  "" ;       
  12.       
  13. public   void  doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)  throws  IOException, ServletException       
  14. {       
  15.            if (encoding !=  null )       
  16.            servletRequest.setCharacterEncoding(encoding);       
  17.           filterChain.doFilter(servletRequest, servletResponse);       
  18. }       
  19.       
  20. public   void  destroy()       
  21. {       
  22.     filterConfig =  null ;       
  23.     encoding =  null ;       
  24. }       
  25.       
  26.        public   void  init(FilterConfig filterConfig)  throws  ServletException       
  27. {       
  28.             this .filterConfig = filterConfig;       
  29.            this .encoding = filterConfig.getInitParameter( "encoding" );       
  30.       
  31. }       
  32. }      


  
四、资源保护过滤器    

  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. //       
  15. import  org.apache.commons.logging.Log;       
  16. import  org.apache.commons.logging.LogFactory;       
  17.       
  18. /**     
  19. * This Filter class handle the security of the application.     
  20. *      
  21. * It should be configured inside the web.xml.     
  22. *      
  23. * @author Derek Y. Shen     
  24. */       
  25. public   class  SecurityFilter  implements  Filter {       
  26. //the login page uri       
  27. private   static   final  String LOGIN_PAGE_URI =  "login.jsf" ;       
  28.         
  29. //the logger object       
  30. private  Log logger = LogFactory.getLog( this .getClass());       
  31.         
  32. //a set of restricted resources       
  33. private  Set restrictedResources;       
  34.         
  35. /**     
  36.    * Initializes the Filter.     
  37.    */       
  38. public   void  init(FilterConfig filterConfig)  throws  ServletException {       
  39.     this .restrictedResources =  new  HashSet();       
  40.     this .restrictedResources.add( "/createProduct.jsf" );       
  41.     this .restrictedResources.add( "/editProduct.jsf" );       
  42.     this .restrictedResources.add( "/productList.jsf" );       
  43. }       
  44.         
  45. /**     
  46.    * Standard doFilter object.     
  47.    */       
  48. public   void  doFilter(ServletRequest req, ServletResponse res, FilterChain chain)       
  49.      throws  IOException, ServletException {       
  50.     this .logger.debug( "doFilter" );       
  51.          
  52.    String contextPath = ((HttpServletRequest)req).getContextPath();       
  53.    String requestUri = ((HttpServletRequest)req).getRequestURI();       
  54.          
  55.     this .logger.debug( "contextPath = "  + contextPath);       
  56.     this .logger.debug( "requestUri = "  + requestUri);       
  57.          
  58.     if  ( this .contains(requestUri, contextPath) && ! this .authorize((HttpServletRequest)req)) {       
  59.      this .logger.debug( "authorization failed" );       
  60.     ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);       
  61.    }       
  62.     else  {       
  63.      this .logger.debug( "authorization succeeded" );       
  64.     chain.doFilter(req, res);       
  65.    }       
  66. }       
  67.         
  68. public   void  destroy() {}        
  69.         
  70. private   boolean  contains(String value, String contextPath) {       
  71.    Iterator ite =  this .restrictedResources.iterator();       
  72.          
  73.     while  (ite.hasNext()) {       
  74.     String restrictedResource = (String)ite.next();       
  75.           
  76.      if  ((contextPath + restrictedResource).equalsIgnoreCase(value)) {       
  77.       return   true ;       
  78.     }       
  79.    }       
  80.          
  81.     return   false ;       
  82. }       
  83.         
  84. private   boolean  authorize(HttpServletRequest req) {       
  85.       
  86.                 //处理用户登录       
  87.          /* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);     
  88.        
  89.    if (user != null && user.getLoggedIn()) {     
  90.     //user logged in     
  91.     return true;     
  92.    }     
  93.    else {     
  94.     return false;     
  95.    }*/       
  96. }       
  97. }    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值