過濾器過濾敏感詞匯的代碼
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
/*
?* 敏感詞匯過濾器
?*/
@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
??? public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
??????? //1.創(chuàng)建代理對(duì)象,增強(qiáng)getParameter方法
??????? ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
??????????? @Override
??????????? public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
??????????????? //增強(qiáng)getParameter方法
??????????????? //判斷是否是getParameter方法
??????????????? if(method.getName().equals("getParameter")){
??????????????????? //增強(qiáng)返回值
??????????????????? //獲取返回值
??????????????????? String value = (String) method.invoke(req,args);
??????????????????? if(value != null){
?????????????????? ??? ?//遍歷敏感字符
??????????????????????? for (String str : list) {
??????????????????????????? if(value.contains(str)){
??????????????????????????????? value = value.replaceAll(str,"***");
??????????????????????????? }
??????????????????????? }
??????????????????? }
?????????????????? ?
??????????????????? return? value;
??????????????? }
??????????????? //判斷方法名是否是 getParameterMap
??????????????? //判斷方法名是否是 getParameterValue
??????????????? return method.invoke(req,args);//如果不是的話傳遞真實(shí)對(duì)象傳遞args數(shù)組
??????????? }
??????? });
??????? //2.放行
??????? chain.doFilter(proxy_req, resp);
??? }
??? private List<String> list = new ArrayList<String>();//敏感詞匯集合
?? ?
?? ?
??? public void init(FilterConfig config) throws ServletException {
??????? try{
??????????? //1.獲取文件真實(shí)路徑
??????????? ServletContext servletContext = config.getServletContext();
??????????? String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感詞匯.txt");
??????????? //2.讀取文件
??????????? BufferedReader br = new BufferedReader(new FileReader(realPath));
??????????? //3.將文件的每一行數(shù)據(jù)添加到list中
??????????? String line = null;
??????????? while((line = br.readLine())!=null){
??????????????? list.add(line);
??????????? }
??????????? br.close();
??????????? System.out.println(list);
??????? }catch (Exception e){
??????????? e.printStackTrace();
??????? }
??? }
??? public void destroy() {
??? }
}
標(biāo)簽: