过滤项目中的非法字符,并且用其他的特殊符号过滤:
WordFilter.java
package com.easyweb.web.character;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.Random;
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;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 过来非法字符的过滤器
*
* @author leo
*
*/
public class WordFilter implements Filter {
Properties ps = new Properties(); // properties 属性文件
Collection con = null; // 非法文字集合(从properties属性文件中读取出来)
private String encoding; // 字符编码
private String[] charWorld = new String[] { "~", "@", "#", "$", "%", "^",
"&", "*" }; // 将非法文字替换成 随机字符
Random input = new Random(); // 随机产生器(为上面的随机字符提供下标)
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (encoding != null) {
request.setCharacterEncoding(encoding); // 设置 request字符编码
request = new Request((HttpServletRequest) request);
response.setContentType("text/html;charset=" + encoding); // 设置response字符编码
}
chain.doFilter(request, response);
}
/**
* 过滤器初始化参数,与读取非法字符的properties文件
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("encoding");
try {
InputStream in = filterConfig.getServletContext().getResourceAsStream("/wordFilter.properties");
ps.load(in);
con = ps.values(); //得到properties中的所有value值,存入collection集合中
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 过滤字符的方法
* @param param
* @return
*/
public String filter(String param) {
// 过滤非法字符的方法
try {
if (param != null && param.length() > 0) {
// 保证传入的字符串不为空和空字符串
Iterator it = con.iterator(); // 迭代器 可以 把collection中的值一条一条的读出来
if (con != null) { // 集合要被初始化
while (it.hasNext()) {
// 判断集合里是否还有值
String value = (String) it.next(); // 取出该值
if (param.indexOf(value) != -1) {
param = param.replace(value, charWorld[input
.nextInt(8)]); // 对非法字符词语进行替换
}
}
}
}
} catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace();
}
return param;
}
//内部类 为了重写request的getParameter 和 getParameterValues
class Request extends HttpServletRequestWrapper{
public Request(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
//返回值之前 先进行过滤
return filter(super.getParameter(name));
}
@Override
public String[] getParameterValues(String name) {
//返回值之前 先进行过滤
String[] values = super.getParameterValues(name);
for (int i = 0; i < values.length; i++) {
values[i] = filter(values[i]);
}
return values;
}
}
}