`
yjlogo
  • 浏览: 46464 次
  • 来自: ...
社区版块
存档分类
最新评论

四个有用的过滤器 Filter

阅读更多
java 代码
  1. 一、使浏览器不缓存页面的过滤器    
  2. import javax.servlet.*;   
  3. import javax.servlet.http.HttpServletResponse;   
  4. import java.io.IOException;   
  5.   
  6. /**  
  7. * 用于的使 Browser 不缓存页面的过滤器  
  8. */  
  9. public class ForceNoCacheFilter implements Filter {   
  10.   
  11. public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException   
  12. {   
  13.    ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");   
  14.    ((HttpServletResponse) response).setHeader("Pragma","no-cache");   
  15.    ((HttpServletResponse) response).setDateHeader ("Expires", -1);   
  16.    filterChain.doFilter(request, response);   
  17. }   
  18.   
  19. public void destroy()   
  20. {   
  21. }   
  22.   
  23.      public void init(FilterConfig filterConfig) throws ServletException   
  24. {   
  25. }   
  26. }   
  27.   
  28. 二、检测用户是否登陆的过滤器   
  29.   
  30. import javax.servlet.*;   
  31. import javax.servlet.http.HttpServletRequest;   
  32. import javax.servlet.http.HttpServletResponse;   
  33. import javax.servlet.http.HttpSession;   
  34. import java.util.List;   
  35. import java.util.ArrayList;   
  36. import java.util.StringTokenizer;   
  37. import java.io.IOException;   
  38.   
  39. /**  
  40. * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面   
  41. * 配置参数   
  42. * checkSessionKey 需检查的在 Session 中保存的关键字  
  43. * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath  
  44. * notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath  
  45. */  
  46. public class CheckLoginFilter   
  47. implements Filter   
  48. {   
  49.      protected FilterConfig filterConfig = null;   
  50.      private String redirectURL = null;   
  51.      private List notCheckURLList = new ArrayList();   
  52.      private String sessionKey = null;   
  53.   
  54. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException   
  55. {   
  56.    HttpServletRequest request = (HttpServletRequest) servletRequest;   
  57.    HttpServletResponse response = (HttpServletResponse) servletResponse;   
  58.   
  59.     HttpSession session = request.getSession();   
  60.    if(sessionKey == null)   
  61.    {   
  62.     filterChain.doFilter(request, response);   
  63.     return;   
  64.    }   
  65.    if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)   
  66.    {   
  67.     response.sendRedirect(request.getContextPath() + redirectURL);   
  68.     return;   
  69.    }   
  70.    filterChain.doFilter(servletRequest, servletResponse);   
  71. }   
  72.   
  73. public void destroy()   
  74. {   
  75.    notCheckURLList.clear();   
  76. }   
  77.   
  78. private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)   
  79. {   
  80.    String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());   
  81.    return notCheckURLList.contains(uri);   
  82. }   
  83.   
  84. public void init(FilterConfig filterConfig) throws ServletException   
  85. {   
  86.    this.filterConfig = filterConfig;   
  87.    redirectURL = filterConfig.getInitParameter("redirectURL");   
  88.    sessionKey = filterConfig.getInitParameter("checkSessionKey");   
  89.   
  90.    String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");   
  91.   
  92.    if(notCheckURLListStr != null)   
  93.    {   
  94.     StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");   
  95.     notCheckURLList.clear();   
  96.     while(st.hasMoreTokens())   
  97.     {   
  98.      notCheckURLList.add(st.nextToken());   
  99.     }   
  100.    }   
  101. }   
  102. }   
  103.   
  104. 三、字符编码的过滤器   
  105.   
  106. import javax.servlet.*;   
  107. import java.io.IOException;   
  108.   
  109. /**  
  110. * 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题  
  111. */  
  112. public class CharacterEncodingFilter   
  113. implements Filter   
  114. {   
  115. protected FilterConfig filterConfig = null;   
  116. protected String encoding = "";   
  117.   
  118. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException   
  119. {   
  120.          if(encoding != null)   
  121.           servletRequest.setCharacterEncoding(encoding);   
  122.          filterChain.doFilter(servletRequest, servletResponse);   
  123. }   
  124.   
  125. public void destroy()   
  126. {   
  127.    filterConfig = null;   
  128.    encoding = null;   
  129. }   
  130.   
  131.      public void init(FilterConfig filterConfig) throws ServletException   
  132. {   
  133.           this.filterConfig = filterConfig;   
  134.          this.encoding = filterConfig.getInitParameter("encoding");   
  135.   
  136. }   
  137. }   
  138.   
  139. 四、资源保护过滤器   
  140.   
  141.   
  142. package catalog.view.util;   
  143.   
  144. import javax.servlet.Filter;   
  145. import javax.servlet.FilterConfig;   
  146. import javax.servlet.ServletRequest;   
  147. import javax.servlet.ServletResponse;   
  148. import javax.servlet.FilterChain;   
  149. import javax.servlet.ServletException;   
  150. import javax.servlet.http.HttpServletRequest;   
  151. import java.io.IOException;   
  152. import java.util.Iterator;   
  153. import java.util.Set;   
  154. import java.util.HashSet;   
  155. //   
  156. import org.apache.commons.logging.Log;   
  157. import org.apache.commons.logging.LogFactory;   
  158.   
  159. /**  
  160.  * This Filter class handle the security of the application.  
  161.  *   
  162.  * It should be configured inside the web.xml.  
  163.  *   
  164.  * @author Derek Y. Shen  
  165.  */  
  166. public class SecurityFilter implements Filter {   
  167.  //the login page uri   
  168.  private static final String LOGIN_PAGE_URI = "login.jsf";   
  169.     
  170.  //the logger object   
  171.  private Log logger = LogFactory.getLog(this.getClass());   
  172.     
  173.  //a set of restricted resources   
  174.  private Set restrictedResources;   
  175.     
  176.  /**  
  177.   * Initializes the Filter.  
  178.   */  
  179.  public void init(FilterConfig filterConfig) throws ServletException {   
  180.   this.restrictedResources = new HashSet();   
  181.   this.restrictedResources.add("/createProduct.jsf");   
  182.   this.restrictedResources.add("/editProduct.jsf");   
  183.   this.restrictedResources.add("/productList.jsf");   
  184.  }   
  185.     
  186.  /**  
  187.   * Standard doFilter object.  
  188.   */  
  189.  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)   
  190.    throws IOException, ServletException {   
  191.   this.logger.debug("doFilter");   
  192.      
  193.   String contextPath = ((HttpServletRequest)req).getContextPath();   
  194.   String requestUri = ((HttpServletRequest)req).getRequestURI();   
  195.      
  196.   this.logger.debug("contextPath = " + contextPath);   
  197.   this.logger.debug("requestUri = " + requestUri);   
  198.      
  199.   if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {   
  200.    this.logger.debug("authorization failed");   
  201.    ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);   
  202.   }   
  203.   else {   
  204.    this.logger.debug("authorization succeeded");   
  205.    chain.doFilter(req, res);   
  206.   }   
  207.  }   
  208.     
  209.  public void destroy() {}    
  210.     
  211.  private boolean contains(String value, String contextPath) {   
  212.   Iterator ite = this.restrictedResources.iterator();   
  213.      
  214.   while (ite.hasNext()) {   
  215.    String restrictedResource = (String)ite.next();   
  216.       
  217.    if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {   
  218.     return true;   
  219.    }   
  220.   }   
  221.      
  222.   return false;   
  223.  }   
  224.     
  225.  private boolean authorize(HttpServletRequest req) {   
  226.   
  227.               //处理用户登录   
  228.        /* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);  
  229.     
  230.   if (user != null && user.getLoggedIn()) {  
  231.    //user logged in  
  232.    return true;  
  233.   }  
  234.   else {  
  235.    return false;  
  236.   }*/  
  237.  }   
  238. }  
    转自:http://hi.baidu.com/samxx8/blog/item/291a788ddb438c10b31bba35.html
分享到:
评论

相关推荐

    Filter-四个有用的Java过滤器

    Filter-四个有用的Java过滤器

    四个有用的java过滤器

    java过滤器 过滤器 J2EE过滤器 filter过滤器

    servlet四个有用的过滤器

    servlet四个有用的过滤器,包括中文转码,缓存过滤等等

    四个有用的Java过滤器收藏

    四个有用的Java过滤器收藏,实用开发的工具类。

    GridControl的过滤器的自定义

    例如,在上述示例中,我们需要使用 "*0" 查询出四个数据记录(1011、010、201、301),但是使用默认的过滤器机制无法实现这种查询操作。这时,我们需要自定义过滤器以满足特定的查询需求。 自定义过滤器的实现 ...

    filter过滤器的简单使用.rar

    这是写的filter过滤器的使用,在maven项目和在springboot项目里面都能使用,并且有使用方法。

    简单理解Struts2中拦截器与过滤器的区别及执行顺序

    在 Struts2 中,过滤器是通过 FilterDispatcher 来实现的,FilterDispatcher 负责四个方面的功能:执行 Actions、清除 ActionContext、维护静态内容和清除 request 生命周期内的 XWork 的 interceptors。 拦截器和...

    5个Servlet过滤器实例源码(JSP)

    Servlet过滤器大全,各种详细使用的代码! 一、字符编码的过滤器 二、使浏览器不缓存页面的过滤器 三、检测用户是否登陆的过滤器 四、资源保护过滤器 五 利用Filter限制用户浏览权限

    Comparing-Filters:对基于Bloom,Cuckoo,Morton和PD的过滤器进行基准测试

    有各种基准可以评估不同负载下的错误概率,并可以通过四个参数进行速度测试:插入,统一查找(标准情况下统一查找结果为“ no” whp),真实查找(过滤器中的元素)和删除。 用法 依存关系 由于CF使用openssl库,...

    过滤器学习笔记一(Filter教你快速入门)

    过滤器的四种拦截方式三:过滤器的应用场景1.案例一:分IP统计访问次数2.案例二:粗粒度权限管理3.案例三:全站编码问题4.案例四:页面静态化(图书管理小项目) 一:过滤器概述 1.什么是过滤器 过滤器是JavaWeb三大...

    同人小说过滤器「FanFic Filter」-crx插件

    添加了字符过滤器,因此用户可以根据字符进行过滤,并且可以选择网站默认过滤器所提供的四个字符限制以外的字符。 还添加了无限滚动功能,因此现在页面将自动加载和过滤,而不必手动浏览有时只有一两个结果的页面。 ...

    table-filter:基于 Bootstrap + JQuery 的 HTML 表格过滤插件

    表过滤器基于 Bootstrap + JQuery 的 HTML 表格过滤器插件,您只需将表格的 id 传递给 tableFilter.filter('id of the table') 方法,点击此按钮将打开一个过滤器弹出窗口一个二 1 三1 one2 二 2 三 2 一个3 二三三...

    fast-guided-filter:何凯明的快速导引过滤器

    快速导引过滤器 何凯明的快速导引过滤器 我们已将其上传到github,目的是使其易于访问开发人员。 原始代码(与该存储库相同)存储在 用于“快速引导过滤器”的Matlab演示代码...运行四个示例以查看本文中显示的结果。

    Particle-Filter:使用粒子过滤器的迷宫机器人定位

    粒子过滤器 雷茂 芝加哥大学 介绍 粒子滤波器是用于解决统计推断问题的蒙特卡洛算法。 在该项目中,使用粒子过滤器推断了乌龟在迷宫中的位置和前进方向。 绿海龟是实际位置,而橙色海龟是估计位置。 箭头是粒子。 ...

    routing-filter 包裹了 Rails 路由系统的复杂野兽,在 Rails URL 识别和生成中提供了看不见的灵活性

    这个库带有四个或多或少的可重用过滤器,并且很容易实现自定义过滤器。也许最受欢迎的一个是 Locale 路由过滤器: Locale- 预先添加页面的 :locale(例如 /de/products) Pagination- 附加 page/:num(例如 /...

    Java-web旅游项目实战案例(四个)IDEA项目源码

    c) Filter:过滤器 d) BeanUtils:数据封装 e) Jackson:json序列化工具 4.2 Service层 f) Javamail:java发送邮件工具 g) Redis:nosql内存数据库 h) Jedis:java的redis客户端 4.3 Dao层 i) Mysql:数据库 j) ...

    Linux下Libpcap源码分析及包过滤机制.pdf

    PF_PACKET类型的socket允许我们把一个名为LPF的过滤器直接放到处理过程中,过滤器在网卡接收中断执行后立即执行。 三、setfilter函数 setfilter函数是Libpcap中用于设置过滤器的函数。该函数首先检查句柄和过滤器...

    Android初学习之intent-filter意图过滤器

    Intent Filter就是用来注册 Activity 、Service 、 Broadcast、Receiver(四大组件) 具有能在某种数据上执行一个动作的能力。使用 Intent Filter ,应用程序组件告诉 Android ,它们能为其它程序的组件的动作请求...

    Linux下Libpcap源码分析及包过滤机制(4).doc

    过滤器安装是包过滤机制的一个重要步骤,涉及到过滤器的安装和配置。在Libpcap中,过滤器安装可以使用setfilter函数来实现,该函数可以将过滤器安装到内核空间中,以便高效地过滤网络数据包。 六、结论 Linux下的...

    java学习-web.xml配置详解实用.pdf

    dispatcher元素用于定义过滤器的请求方式,可以是REQUEST、INCLUDE、FORWARD或ERROR 四种,默认为 REQUEST。 web.xml文件是Java Web应用程序的核心配置文件,用于定义Web应用程序的各种配置信息。通过学习web.xml...

Global site tag (gtag.js) - Google Analytics