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

4个有用的filter

    博客分类:
  • j2ee
阅读更多

转载自http://www.blogjava.net/fantasy/archive/2006/03/21/36593.html

 

 

一、使浏览器不缓存页面的过滤器

 

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;

/**
 * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面<p>
 * 配置参数<p>
 * checkSessionKey 需检查的在 Session 中保存的关键字<br/>
 * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath<br/>
 * notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath<br/>
 */
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;
		}*/
	}
}
 

 

 

 

 

 

分享到:
评论

相关推荐

    Filter4个有用的过滤器

    很详细的代码,非常有用,都是开发中常用的几种拦截器!

    java中filter的用法(过滤器)

    #### 四、配置Filter Filter需要在web.xml文件中进行配置,配置主要包括Filter的类名、初始化参数以及拦截的URL模式。 ```xml &lt;filter&gt; &lt;filter-name&gt;ForceNoCacheFilter&lt;/filter-name&gt; &lt;filter-class&gt;...

    java filter打印请求返回参数

    这种方法不仅能够帮助我们更好地理解和调试程序逻辑,还能为后续的日志记录和性能分析提供有用的信息。此外,通过对请求和响应的封装,我们还能解决一些常见的编码问题,提高系统的健壮性和用户体验。

    Bloom Filter概念和原理

    Bloom Filter是一种非常有用且高效的数据结构,在许多场景中都能发挥重要作用。通过合理设计Bloom Filter的参数,可以在保持较低误报率的同时实现存储空间的有效利用。随着技术的发展,Bloom Filter也在不断地演变和...

    matlab中filter conv impz用法

    例如,`filter([1,2],1,[1,2,3,4,5])`实现了`y[k] = x[k] + 2*x[k-1]`这个差分方程,其中`y`是输出序列。 其次,`conv`函数用于计算两个序列的卷积。卷积是信号处理中的基本运算,它反映了输入信号经过某一系统后的...

    Filter-四个有用的Java过滤器

    在给定的文件中,提到了四个有用的Java过滤器实例,分别是: 1. **使浏览器不缓存页面的过滤器**: 这个过滤器的目的是防止用户浏览器缓存页面,确保每次请求都能获取服务器最新的内容。它通过设置HTTP响应头来...

    delphi资源-Filter中的模糊过滤

    4. **范围限定**:对于复杂的条件组合,需要明确地使用括号来限定每个子条件的范围,例如`((Field1 = "AAA") AND (Field2 = "TTT")) OR ((Field1 = "BBB") AND (Field2 = "TTT"))`。 #### 四、具体实现方法 ##### ...

    FilterPro软件学习

    3. **滤波器比较**:FilterPro允许同时设计和比较多个滤波器,帮助用户在不同设计方案间做出决策。这在项目开发和优化过程中非常有用。 4. **实时仿真**:用户可以对设计的滤波器进行实时仿真,查看输入信号经过...

    NDIS-filter.rar_NDIS Filter_Windows NDIS Filter_filter_ndis_ndis

    这个特性在网络安全、性能监测和网络管理应用中非常有用。 "NDIS-filter.rar_NDIS Filter_Windows NDIS Filter_filter_ndis_ndis"这个压缩包包含的资源是关于NDIS Filter驱动的实例,其中"NDisMonitor_v1-00"和...

    TS File source filter

    描述提到“为了在graphEdit中访问ts文件,这是一个非常有用的源代码”。GraphEdit是微软DirectShow开发工具,允许开发者构建和测试多媒体处理图形过滤器图。通过这个源代码,开发者能够创建自定义过滤器来读取和处理...

    java-bloomfilter

    布隆过滤器在处理大数据时特别有用,因为它可以在内存有限的情况下,快速、大概率地判断一个元素是否存在,虽然可能会有误判的情况,但不会漏判。 布隆过滤器的基本原理是通过多个哈希函数将元素映射到一个位数组中...

    bp_filter.rar_bp filter_bp_filter_地震_地震 滤波_滤波 地震

    "bp_filter.rar"这个压缩包包含了一个名为"bp_filter"的MATLAB源码程序,专门用于实现带通滤波功能,它针对地震数据进行了优化。带通滤波器允许在特定频率范围内通过信号,同时抑制频率范围之外的信号噪声,这对于...

    tablefilter

    4. **ADF Faces Test**:这个文件名可能是指一个测试项目或示例,展示了如何在ADF Faces中使用TableFilter功能。开发者可以通过这个例子学习如何配置和使用TableFilter,包括定义过滤条件、处理过滤事件、以及更新...

    Filter Solutions WIN8

    4. **模拟与比较**:Filter Solutions允许用户模拟不同的滤波器设计并进行比较,以便选择最佳方案。这种对比功能对于优化设计和解决问题非常有用。 5. **图形化界面**:软件采用直观的图形用户界面,使得操作流程...

    filter.rar_filter_matlab filter_source filter speech_speech reco

    压缩包内的"filter4.pdf"文件可能是详细阐述滤波器设计或语音识别方法的文档,可能涵盖了滤波器设计的基本原理,例如IIR(无限 impulse response)和FIR(有限 impulse response)滤波器的实现,以及在MATLAB中如何...

    filter_pcd.zip

    标题中的"filter_pcd.zip"表明这是一个与处理点云数据(Point Cloud Data)相关的压缩文件。在3D计算机视觉和机器人领域,点云数据是一种常用的数据形式,它由多个三维坐标点组成,用来描述物体表面的形状。...

    swift map,reduce,filter,flatmap

    在Swift中,`map`、`reduce`、`filter`和`flatMap`是四个非常重要的高阶函数,它们是函数式编程的核心概念,能帮助我们以更简洁、更可读的方式处理集合数据。在这篇文章中,我们将深入探讨这四个函数的使用方法和...

    Gaborfilter_MATLAB检测_Gaborfilter_

    通过运行这两个脚本,我们可以观察不同参数下的滤波效果,理解Gabor滤波器如何帮助我们从图像中提取有用信息。 总的来说,Gabor滤波器结合MATLAB的强大功能,为图像处理提供了一种有效的方法,尤其是在边缘检测中。...

    logstash-filter-geoip-cn.zip

    3. **数据增强**:除了IP地址,你还可以获得其他有用的信息,如时区、ISP、邮政编码等,这些都可以用于进一步的数据分析和报告。 4. **日志分析**:对于网络监控和安全分析,了解请求来源的地理位置(现在是中文...

    Ext grid filter

    这个组件极大地提高了数据的可搜索性和用户交互性,尤其在处理大量数据时非常有用。 在Ext JS中,Grid是一个显示二维数据的组件,它由行和列组成,每个单元格存储一个数据项。Filter功能则为每列提供了条件过滤,...

Global site tag (gtag.js) - Google Analytics