`
yufenfei
  • 浏览: 801096 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

五个有用的过滤器 Filter

阅读更多

一、使浏览器不缓存页面的过滤器    
import javax.servlet.*;   
import javax.servlet.http.HttpServletResponse;   
import java.io.IOException;   
  
/**  
* 用于的使 Browser 不缓存页面的过滤器  
*/  
public class ForceNoCacheFilter implements Filter {   
  
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,

ServletException   
{   
   ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");   
   ((HttpServletResponse) response).setHeader("Pragma","no-cache");   
   ((HttpServletResponse) response).setDateHeader ("Expires", -1);   
   filterChain.doFilter(request, response);   
}   
  
public void destroy()   
{   
}   
  
     public void init(FilterConfig filterConfig) throws ServletException   
{   
}   
}   
  
二、检测用户是否登陆的过滤器   
  
import javax.servlet.*;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
import javax.servlet.http.HttpSession;   
import java.util.List;   
import java.util.ArrayList;   
import java.util.StringTokenizer;   
import java.io.IOException;   
  
/**  
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面   


* 配置参数   


* checkSessionKey 需检查的在 Session 中保存的关键字  

* redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath  

* notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath  

*/  
public class CheckLoginFilter   
implements Filter   
{   
     protected FilterConfig filterConfig = null;   
     private String redirectURL = null;   
     private List notCheckURLList = new ArrayList();   
     private String sessionKey = null;   
  
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws

IOException, ServletException   
{   
   HttpServletRequest request = (HttpServletRequest) servletRequest;   
   HttpServletResponse response = (HttpServletResponse) servletResponse;   
  
    HttpSession session = request.getSession();   
   if(sessionKey == null)   
   {   
    filterChain.doFilter(request, response);   
    return;   
   }   
   if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)   
   {   
    response.sendRedirect(request.getContextPath() + redirectURL);   
    return;   
   }   
   filterChain.doFilter(servletRequest, servletResponse);   
}   
  
public void destroy()   
{   
   notCheckURLList.clear();   
}   
  
private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)   
{   
   String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());   
   return notCheckURLList.contains(uri);   
}   
  
public void init(FilterConfig filterConfig) throws ServletException   
{   
   this.filterConfig = filterConfig;   
   redirectURL = filterConfig.getInitParameter("redirectURL");   
   sessionKey = filterConfig.getInitParameter("checkSessionKey");   
  
   String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");   
  
   if(notCheckURLListStr != null)   
   {   
    StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");   
    notCheckURLList.clear();   
    while(st.hasMoreTokens())   
    {   
     notCheckURLList.add(st.nextToken());   
    }   
   }   
}   
}   
  
三、字符编码的过滤器   
  
import javax.servlet.*;   
import java.io.IOException;   
  
/**  
* 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题


*/  
public class CharacterEncodingFilter   
implements Filter   
{   
protected FilterConfig filterConfig = null;   
protected String encoding = "";   
  
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws

IOException, ServletException   
{   
         if(encoding != null)   
          servletRequest.setCharacterEncoding(encoding);   
         filterChain.doFilter(servletRequest, servletResponse);   
}   
  
public void destroy()   
{   
   filterConfig = null;   
   encoding = null;   
}   
  
     public void init(FilterConfig filterConfig) throws ServletException   
{   
          this.filterConfig = filterConfig;   
         this.encoding = filterConfig.getInitParameter("encoding");   
  
}   
}   
  
四、资源保护过滤器   
  
  
package catalog.view.util;   
  
import javax.servlet.Filter;   
import javax.servlet.FilterConfig;   
import javax.servlet.ServletRequest;   
import javax.servlet.ServletResponse;   
import javax.servlet.FilterChain;   
import javax.servlet.ServletException;   
import javax.servlet.http.HttpServletRequest;   
import java.io.IOException;   
import java.util.Iterator;   
import java.util.Set;   
import java.util.HashSet;   
//   
import org.apache.commons.logging.Log;   
import org.apache.commons.logging.LogFactory;   
  
/**  
* This Filter class handle the security of the application.  
*   
* It should be configured inside the web.xml.  
*   
* @author Derek Y. Shen  
*/  
public class SecurityFilter implements Filter {   
//the login page uri   
private static final String LOGIN_PAGE_URI = "login.jsf";   
    
//the logger object   
private Log logger = LogFactory.getLog(this.getClass());   
    
//a set of restricted resources   
private Set restrictedResources;   
    
/**  
* Initializes the Filter.  
*/  
public void init(FilterConfig filterConfig) throws ServletException {   
this.restrictedResources = new HashSet();   
this.restrictedResources.add("/createProduct.jsf");   
this.restrictedResources.add("/editProduct.jsf");   
this.restrictedResources.add("/productList.jsf");   
}   
    
/**  
* Standard doFilter object.  
*/  
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)   
   throws IOException, ServletException {   
this.logger.debug("doFilter");   
     
String contextPath = ((HttpServletRequest)req).getContextPath();   
String requestUri = ((HttpServletRequest)req).getRequestURI();   
     
this.logger.debug("contextPath = " + contextPath);   
this.logger.debug("requestUri = " + requestUri);   
     
if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {   
   this.logger.debug("authorization failed");   
   ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);   
}   
else {   
   this.logger.debug("authorization succeeded");   
   chain.doFilter(req, res);   
}   
}   
    
public void destroy() {}    
    
private boolean contains(String value, String contextPath) {   
Iterator ite = this.restrictedResources.iterator();   
     
while (ite.hasNext()) {   
   String restrictedResource = (String)ite.next();   
      
   if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {   
    return true;   
   }   
}   
     
return false;   
}   
    
private boolean authorize(HttpServletRequest req) {   
  
              //处理用户登录   
       /* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);  
    
if (user != null && user.getLoggedIn()) {  
   //user logged in  
   return true;  
}  
else {  
   return false;  
}*/  
}   
}  
五 利用Filter限制用户浏览权限

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

改的话只需要在Filter文件里动下就可以。
以下是Filter文件代码:

import java.io.IOException;   
  
import javax.servlet.Filter;   
import javax.servlet.FilterChain;   
import javax.servlet.FilterConfig;   
import javax.servlet.ServletException;   
import javax.servlet.ServletRequest;   
import javax.servlet.ServletResponse;   
import javax.servlet.http.HttpServletRequest;   
  
public class RightFilter implements Filter {   
  
    public void destroy() {   
           
    }   
  
    public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException,

ServletException {   
        // 获取uri地址   
        HttpServletRequest request=(HttpServletRequest)sreq;   
        String uri = request.getRequestURI();   
        String ctx=request.getContextPath();   
        uri = uri.substring(ctx.length());   
        //判断admin级别网页的浏览权限   
        if(uri.startsWith("/admin")) {   
            if(request.getSession().getAttribute("admin")==null) {   
                request.setAttribute("message","您没有这个权限");   
                request.getRequestDispatcher("/login.jsp").forward(sreq,sres);   
                return;   
            }   
        }   
        //判断manage级别网页的浏览权限   
        if(uri.startsWith("/manage")) {   
            //这里省去   
            }   
        }   
        //下面还可以添加其他的用户权限,省去。   
  
    }   
  
    public void init(FilterConfig arg0) throws ServletException {   
           
    }   
  
}  
<!-- 判断页面的访问权限 -->  
<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的配置,如下:
<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,不然过滤器也起不了作用。

分享到:
评论

相关推荐

    过滤器(Filter)

    在IT行业中,过滤器(Filter)是一个非常重要的概念,尤其在Web开发领域。过滤器机制是Java Servlet规范的一部分,它允许开发者对HTTP请求和响应进行拦截处理,而不干扰实际的请求处理流程。过滤器可以用来实现诸如...

    过滤器Filter的全面解析

    总的来说,Java Web中的过滤器Filter是一种强大的工具,它可以帮助开发者在不改变原有业务逻辑的情况下,增加额外的功能和控制,提高了代码的可维护性和灵活性。理解并熟练掌握过滤器的使用,对于任何J2EE开发者来说...

    Filter(过滤器)简介和工作原理

    Filter(过滤器)简介和工作原理 Filter 简介 Filter(过滤器)是 Java EE 中的一种组件,用于拦截和处理 Servlet 容器中的请求和响应。Filter 的基本功能是对 Servlet 容器调用 Servlet 的过程进行拦截,从而在 ...

    java 中如何使用filter过滤器

    在Java Web开发中,Filter(过滤器)是一个强大的工具,它允许开发者在数据处理的前后进行拦截和修改。本文将详细介绍如何在Java中使用Filter过滤器,以及如何配置相关的配置文件,让你一目了然。 ### 1. Filter...

    过滤器(filter) 例子源码

    在Java Web开发中,过滤器(Filter)是一个非常重要的组件,它允许开发者在请求被处理之前或之后执行一些预定义的任务。本篇文章将基于提供的标题和描述,详细讲解过滤器的概念、工作原理以及如何通过源码实现一个...

    如何配置Filter过滤器处理JSP中文乱码

    解决这个问题的一种常见方法是使用Filter过滤器。以下是配置Filter过滤器处理JSP中文乱码的详细步骤: 1. **配置web.xml文件** 在项目的`web.xml`文件中,你需要添加一个Filter来定义处理乱码的逻辑。首先,声明一...

    spring-boot 过滤器 filter

    1. 实现`javax.servlet.Filter`接口:创建一个类,实现`doFilter()`方法,然后在`WebApplicationInitializer`或`WebMvcConfigurer`接口的实现类中注册该过滤器。 ```java public class MyFilter implements Filter ...

    servlet过滤器Filter入门

    建立一个过滤器需要五个步骤: * 建立一个实现 Filter 接口的类。 * 在 doFilter 方法中放入过滤行为。 * 调用 FilterChain 对象的 doFilter 方法。 * 对相应的 servlet 和 JSP 页面注册过滤器。 * 禁用激活器 ...

    AngularJS过滤器filter

    **AngularJS过滤器filter详解** AngularJS是一款强大的前端JavaScript框架,用于构建动态Web应用程序。过滤器是AngularJS中一个至关重要的特性,它允许我们在数据展示时进行格式化和转换,从而提升用户体验。过滤器...

    javaFilter自定义编码过滤器

    Filter 接口用于定义一个过滤器, FilterChain 接口用于将多个过滤器连接起来,以便实现链式调用。 * Filter 接口: Filter 接口是 Java 中的一种过滤器接口,用于对 HttpServletRequest 和 HttpServletResponse ...

    ffmpeg filter过滤器基础实例以及全面解析

    FFmpeg Filter 过滤器是FFmpeg项目中用于音视频数据处理的一个重要组件,通过libavfilter库提供丰富的视频和音频过滤功能。这些过滤器可以在不同阶段对媒体数据进行操作,包括但不限于格式转换、帧率调整、大小缩放...

    filter过滤器防止恶意注入

    在Java Web开发中,`Filter`过滤器是一个关键的安全组件,用于拦截并处理HTTP请求和响应。本示例中的`URLfilter`类就是一个简单的过滤器,它的主要目的是防止SQL注入攻击,这是一种常见的恶意攻击手段,攻击者试图...

    SpringBoot的filter过滤器(源代码)

    SpringBoot的filter过滤器 一、过滤器的作用和概述 1.1 简述 1.2 使用场景 二、自定义过滤的两种方式 2.1 第一种方式 2.1.1 启动类增加注解@ServletComponentScan 2.1.2 定义一个filter类 2.1.3. 测试 2.2 第二种...

    bloom filter(C#版自制布隆过滤器)

    布隆过滤器是一种空间效率极高的概率型数据结构,用于判断一个元素是否可能在一个集合中。它是由 Burton Howard Bloom 在1970年提出的,主要应用于大数据存储和检索,尤其在数据库、缓存系统和网络搜索等领域有广泛...

    ssh框架乱码过滤器Filter

    创建一个自定义过滤器,我们首先要继承`javax.servlet.Filter`接口,并实现其`doFilter()`方法。在该方法中,我们需要获取到请求(HttpServletRequest)和响应(HttpServletResponse),然后设定合适的字符编码。...

    Filter-四个有用的Java过滤器

    Java过滤器(Filter)是Java Web开发中的一个重要概念,它属于Servlet技术的一部分,主要用于处理HTTP请求和响应。在给定的文件中,提到了四个有用的Java过滤器实例,分别是: 1. **使浏览器不缓存页面的过滤器**:...

    用户登陆过滤器

    在这个过滤器中,我们可以看到它主要由两部分组成:一部分是web.xml中的配置,另一部分是Java代码中的实现。 首先,在web.xml中,我们可以看到filter的配置,包括filter-name和filter-class两个参数。filter-name是...

    j2ee过滤器Filter使用详解(实例)

    本文将深入解析J2EE过滤器Filter的使用方法,并通过实例来阐述其工作原理。 过滤器在J2EE环境中扮演着预处理和后处理的角色,它可以拦截进入和离开Web应用程序的请求和响应,对数据进行处理或验证,从而提供诸如...

    Filter过滤器(分类讨论,分类讲解)

    ### Filter过滤器(分类讨论,分类讲解) #### 一、Filter概述 在Java Web开发中,`Filter`是一种非常重要的技术,它可以在请求到达目标资源(如Servlet或JSP页面)之前进行预处理,或者在响应返回客户端之前进行...

Global site tag (gtag.js) - Google Analytics