日期:2014-05-17  浏览次数:20819 次

新手问个小过滤器程序问题
是这样,定义了一个要过滤的字符串组String[]{"你妈","傻逼 "};
当提交页面后 显示提交的内容,如果有上面字符串组的内容 即用***代替,
测试过后,问题是 只有“你妈”被过滤掉了,而傻逼没有,求助
Java code

package com.lyq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class wordFilter implements Filter {
    private String words[];

    public void destroy() {
        // TODO Auto-generated method stub
        this.words=null;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        request=new Request((HttpServletRequest)request);
        response.setContentType("text/html;charset="+"UTF-8");
        chain.doFilter(request, response);

    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        words=new String[]{"你妈","傻逼 "};

    }
    public String filter(String ss){
        try{
            if(words!=null){
                for(int i=0;i<words.length;i++){
                    if(ss.indexOf(words[i])!=-1){
                        ss=ss.replace(words[i], "***");
                    }
                }
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return ss;
    }
    class Request extends HttpServletRequestWrapper {
        public Request(HttpServletRequest request){
            super(request);
        }

        @Override
        public String getParameter(String name) {
            // TODO Auto-generated method stub
            return filter(super.getRequest().getParameter(name));
        }

        @Override
        public String[] getParameterValues(String name) {
            // TODO Auto-generated method stub
            String []values=super.getRequest().getParameterValues(name);
            for(int i=0;i<values.length;i++){
                values[i]=filter(values[i]);
            }
                return values;
        }
        

    }

}




------解决方案--------------------
String[]{"你妈","傻逼 "};
"傻逼 "后面多了一个空格