JAVA 特殊字符过滤器

public class SpecialCharacterFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings({ "unchecked", "null" })
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		Map map = request.getParameterMap(); //获取request里面所有请求参数。已Key-value形式返回
		if(map!=null||map.size()<1){   //有参数时才处理
			Set set = map.entrySet();
			Iterator ite = set.iterator(); //返回迭代器
			while(ite.hasNext()){   //迭代替换参数中的特殊字符
				Map.Entry entry = (Entry) ite.next();
				if(entry.getValue() instanceof String[]){
					   String[] values = (String[]) entry.getValue();  
			      for(int i = 0 ; i < values.length ; i++){  
			       values[i] = StringFilter(values[i]);  
			      }
			      entry.setValue(values);  //存进参数集合中
				}
			}
	
		}
		
		arg2.doFilter(arg0, arg1);	  //放行
		}


	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
   
	
  public  String StringFilter(String   str){     
  String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?\"\"]";  
  Pattern   p   =   Pattern.compile(regEx);     
  Matcher   m   =   p.matcher(str);     
  return   m.replaceAll("").trim();     
  }  
}

你可能感兴趣的:(JAVA 特殊字符过滤器)