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

    五 利用Filter限制用户浏览权限

    在一个系统中通常有多个权限的用户。不同权限用户的可以浏览不同的页面。使用Filter进行判断不仅省下了代码量,而且如果要更改的话只需要在Filter文件里动下就可以。 以下是Filter文件代码:

    1. import java.io.IOException;     
    2.   
    3.     
    4. import javax.servlet.Filter;     
    5. import javax.servlet.FilterChain;     
    6. import javax.servlet.FilterConfig;     
    7. import javax.servlet.ServletException;     
    8. import javax.servlet.ServletRequest;     
    9. import javax.servlet.ServletResponse;     
    10. import javax.servlet.http.HttpServletRequest;     
    11.     
    12. public class RightFilter implements Filter {     
    13.     
    14.     public void destroy() {     
    15.              
    16.      }     
    17.     
    18.     public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException, ServletException {     
    19.         // 获取uri地址     
    20.          HttpServletRequest request=(HttpServletRequest)sreq;     
    21.          String uri = request.getRequestURI();     
    22.          String ctx=request.getContextPath();     
    23.          uri = uri.substring(ctx.length());     
    24.         //判断admin级别网页的浏览权限     
    25.         if(uri.startsWith("/admin")) {     
    26.             if(request.getSession().getAttribute("admin")==null) {     
    27.                  request.setAttribute("message","您没有这个权限");     
    28.                  request.getRequestDispatcher("/login.jsp").forward(sreq,sres);     
    29.                 return;     
    30.              }     
    31.          }     
    32.         //判断manage级别网页的浏览权限     
    33.         if(uri.startsWith("/manage")) {     
    34.             //这里省去     
    35.              }     
    36.          }     
    37.         //下面还可以添加其他的用户权限,省去。     
    38.     
    39.      }     
    40.     
    41.     public void init(FilterConfig arg0) throws ServletException {     
    42.              
    43.      }     
    44.     
    45. }   
    1. <!-- 判断页面的访问权限 -->    
    2.   <filter>    
    3.      <filter-name>RightFilter</filter-name>    
    4.       <filter-class>cn.itkui.filter.RightFilter</filter-class>    
    5.   </filter>    
    6.   <filter-mapping>    
    7.       <filter-name>RightFilter</filter-name>    
    8.       <url-pattern>/admin/*</url-pattern>    
    9.   </filter-mapping>    
    10.   <filter-mapping>    
    11.       <filter-name>RightFilter</filter-name>    
    12.       <url-pattern>/manage/*</url-pattern>    
    13.   </filter-mapping>    

    在web.xml中加入Filter的配置,如下:

    1. <filter>  
    2.     <filter-name>EncodingAndCacheflush</filter-name>    
    3.     <filter-class>EncodingAndCacheflush</filter-class>    
    4.     <init-param>    
    5.         <param-name>encoding</param-name>    
    6.         <param-value>UTF-8</param-value>    
    7.     </init-param>    
    8. </filter>    
    9. <filter-mapping>    
    10.     <filter-name>EncodingAndCacheflush</filter-name>    
    11.     <url-pattern>/*</url-pattern>    
    12. </filter-mapping>     

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

  • 相关阅读:
    Core 1.0中的管道-中间件模式
    java平台的常用资源
    C#设备处理类操作
    C#语音录制
    Web中的性能优化
    nginx+lua+redis构建高并发应用(转)
    HttpLuaModule——翻译(Nginx API for Lua) (转)
    Nginx各版本的区别
    Linux(Centos)中tcpdump参数用法详解(转)
    我见过最好的vsftpd配置教程(转)
  • 原文地址:https://www.cnblogs.com/wangorg/p/5045617.html
Copyright © 2011-2022 走看看