过滤器心得及实现

过滤器

  1. 过滤器位于客户端和Web应用程序之间,用于检查和修改两者之间流过的请求和响应。
  2. 在请求到达Servlet/JSP之前,过滤器会截获请求。
  3. 在响应送给客户端之前,过滤器截获响应
  4. 多个过滤器形成一个过滤器链,过滤器链中不同过滤器的先后顺序由部署文件web.xml中过滤器映射<filter-mapping>的顺序决定。
  5. 最先截获客户端请求的过滤器将最后截获Servlet/JSP的响应信息。
  6. 我们也可以为一个Web应用组件部署多个过滤器链,每个过滤器只执行某个特定的操作或检查。这样请求在到达被访问的目标前,需要经过这个过滤器链。具体流程的话,我们可以参考递归。

具体实现

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>WishingWall</display-name>
  <!-- 敏感字过滤器 -->
  <filter>
	 <filter-name>ContentFilter</filter-name>
	 <filter-class>
	 	com.etc.filter.ContentFilter
	 </filter-class>
	 <init-param>
		 <param-name>filePath</param-name>
		 <param-value>/WEB-INF/words</param-value>
	 </init-param>
</filter>
 <filter-mapping>
	 <filter-name>ContentFilter</filter-name>
	 <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

ContentFilter
package com.yby.filter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class ContentFilter implements Filter{

	private Map<String, String> map=new HashMap<String, String>();
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		
		String filePath=config.getInitParameter("filePath");//从配置文件种获取到文件的相对路径/WEB-INF/words
		ServletContext context=config.getServletContext();//读取上下文环境
		String realPath=context.getRealPath(filePath);//绝对路径
		FileReader fr=null;
		BufferedReader br=null;
		
		try {
			fr=new FileReader(realPath);
			br=new BufferedReader(fr);
			String line=null;
			while((line=br.readLine())!=null) {
				String[] str=line.split("==");//根据==进行拆分字符串
				map.put(str[0], str[1]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
			try {
				if(br!=null) {
					br.close();
				}
				if(fr!=null) {
					fr.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse resonpse, FilterChain filterChain)
			throws IOException, ServletException {
		//处理请求中的数据
		HttpRequestWrapper hrw=new HttpRequestWrapper((HttpServletRequest)request);
		hrw.setMap(map);	
		filterChain.doFilter(hrw, resonpse);
	}

	@Override
	public void destroy() {
		this.map=null;
	}

}

HttpRequestWrapper
package com.yby.filter;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/*http请求包装类*/
public class HttpRequestWrapper extends HttpServletRequestWrapper {

	private Map<String, String> map=null;
	
	public HttpRequestWrapper(HttpServletRequest request) {
		super(request);
	}
	public String replace(String str) {
		StringBuffer sb=new StringBuffer(str);
		Set<String> keys=this.getMap().keySet();//key为敏感字集合
		Iterator<String> it=keys.iterator();
		String ss=null;//存储key变量
		while(it.hasNext()) {
			String key=it.next();
			int index=sb.indexOf(key);//查找字符串中是否存在需要替换的文字
			if(index!=-1) {
				if(key!=null) {
					ss=key;
				}
				sb.replace(index, index+key.length(),this.getMap().get(key) );
			}
		}
		
		if(ss!=null) {//确保已经替换完毕
			if(sb.toString().indexOf(ss)==-1) {
				return sb.toString();
			}else {
				return replace(sb.toString());
			}
		}
		return sb.toString();
	}
	
	//重写getParameter方法
	public String getParameter(String str) {
		if(str.equals("pager.offset")) {//分页的信息不做处理的话可以这么处理
			return super.getParameter(str);
		}else {
			String content=super.getParameter(str);
			return replace(content);//返回被替换的文字
		}
	}
	

	public Map<String, String> getMap() {
		return map;
	}

	public void setMap(Map<String, String> map) {
		this.map = map;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值