posts - 3, comments - 0, trackbacks - 0, articles - 1

TOMCAT 全局过滤

Posted on 2013-03-01 17:33 whitesky 阅读(502) 评论(0)  编辑  收藏
    import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MyHttpRequestWrapper extends HttpServletRequestWrapper {
    byte[] buffer = null;
    private ServletInputStream in = null;
    private BufferedReader reader = null;
    private boolean isMultipart = false;
    private String contentType = null;

    public MyHttpRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        contentType = request.getHeader("Content-Type");
        if (contentType != null
                && contentType.startsWith("multipart/form-data")) {
            isMultipart = true;// fileupload
            readInputStream(request);
            // read end and wrapper buffer
            ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);// real
                                                                                
// servletInputStream
            in = new WrapperServletInputstream(inputStream);
            reader = new BufferedReader(new InputStreamReader(inputStream));
        }
    }

    /**
     * 读取request流到buffer中
     * 
     * 
@param request
     *            HttpServletRequest
     * 
@throws IOException
     *             if throws IOException
     
*/
    private void readInputStream(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        ServletInputStream sis = request.getInputStream();
        int maxReadSize = 1024;// buffer size
        buffer = new byte[contentLength];
        int end = 0;
        int len = 0;
        while (end <= contentLength) {
            len = sis.read(buffer, end, maxReadSize);
            if (len == -1) {
                end = contentLength;
                break;
            }
            end += len;
            try {
                TimeUnit.MILLISECONDS.sleep(0);// 轮询
            } catch (InterruptedException e) {
                // ignroe
            }
        }
        sis.close();// closed?
    }

    /**
     * if isMultipart return request inputstream to byte[]
     * 
     * 
@return default null
     
*/
    public byte[] getRequestData() {
        return buffer;
    }

    // 重载父类获取inputStream的方法
    @Override
    public ServletInputStream getInputStream() throws IOException {
        return isMultipart ? in : super.getInputStream();
    }

    // 重载父类获取reader的方法
    @Override
    public BufferedReader getReader() throws IOException {
        return isMultipart ? reader : super.getReader();
    }

    /**
     * 判断此次请求是否是上传文件
     * 
     * 
@return
     
*/
    public boolean isMultipart() {
        return isMultipart;
    }

    public String getRequestInfo() {
        Enumeration parameterNames = getParameterNames();
        StringBuilder parameterInfo = new StringBuilder();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement().toString();
            String[] parameters = getParameterValues(name);
            parameterInfo.append(name).append(":[");
            for (String str : parameters) {
                parameterInfo.append(str).append(",");
            }
            if (parameters.length > 0) {
                parameterInfo.deleteCharAt(parameterInfo.length() - 1);
            }
            parameterInfo.append("]\n");
        }
        Enumeration headerNames = getHeaderNames();
        StringBuilder headerInfo = new StringBuilder();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement().toString();
            Enumeration headers = getHeaders(name);
            headerInfo.append(name).append(":");
            while (headers.hasMoreElements()) {
                headerInfo.append(headers.nextElement()).append(" ");
            }
            headerInfo.append("\n");
        }
        StringBuilder cookies = new StringBuilder();
        // for (int i = 0;i<getCookies().length;i++) {
        
// Cookie cookie = getCookies()[i];
        
// if(cookie==null){
        
// continue;
        
// }
        
// cookies.append(cookie.getName()).append(":").append(
        
// cookie.getValue()).append("\n");
        
// }
        StringBuilder requestInfo = new StringBuilder().append(parameterInfo)
                .append(headerInfo).append(cookies);
        return requestInfo.toString();
    }

    class WrapperServletInputstream extends ServletInputStream {
        private InputStream in = null;

        public WrapperServletInputstream(InputStream in) throws IOException {
            this.in = in;
        }

        @Override
        public int read() throws IOException {
            int read = in.read();
            return read;
        }

        @Override
        public synchronized void reset() throws IOException {
            in.reset();
            super.reset();
        }
    }

}import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class MyHttpResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;
    private boolean usingStream = false;
    private boolean usingWriter = false;

    public MyHttpResponseWrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        buffer = new ByteArrayOutputStream();// 真正存储数据的流
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer, "UTF-8"));
    }
    // 重载父类获取outputstream的方法
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        usingStream = true;
        return out;
    }
    // 重载父类获取writer的方法
    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        usingWriter = true
        return writer;
    }
    // 重载父类获取flushBuffer的方法
    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }
    @Override
    public void reset() {
        buffer.reset();
    }
    public byte[] getResponseData() throws IOException {
        // 将out、writer中的数据强制输出到WapperedResponse的buffer里面,否则取不到数据
        flushBuffer();
        return buffer.toByteArray();
    }

    // 内部类,对ServletOutputStream进行包装
    private class WapperedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;
        public WapperedOutputStream(ByteArrayOutputStream stream)
                throws IOException {
            bos = stream;
        }
        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }
    }

    public boolean isUsingStream() {
        return usingStream;
    }
    public boolean isUsingWriter() {
        return usingWriter;
    }

}// --------获取请求内容------------------
        MyHttpRequestWrapper httpRequestWrapper = new MyHttpRequestWrapper(
                request);// 获取request请求内容
        MyHttpResponseWrapper httpResponseWrapper = new MyHttpResponseWrapper(
                response);// 装饰HttpServletRequest
        boolean passResponse = true;// 是否通过响应,默认是
        chain.doFilter(httpRequestWrapper, httpResponseWrapper);
        String encode = httpRequestWrapper.getCharacterEncoding();
        encode = encode == null ? Constant.default_charset : encode;
        String request_content = null;
        if (httpRequestWrapper.isMultipart()) {// 文件上传内容为byte[]
            request_content = new String(httpRequestWrapper.getRequestData(),
                    encode);
        } else {// 普通上传内容
            request_content = httpRequestWrapper.getRequestInfo();
            // System.out.println("普通上传内容:"+request_content);
        }
        passRequest = !checkHtml.check_html(fullURL, request_content);
        if (passRequest) {
            System.out.println("passRequest:" + fullURL);
        } else {
            System.out.println("request contain keywords:" + fullURL);
            // sendErrorPage(httpRequestWrapper, response);//不转跳 记录日志到数据库就可以了
            popupMessage(httpRequestWrapper, httpResponseWrapper);
            return;
        }
        byte[] response_data = httpResponseWrapper.getResponseData();
        if (httpResponseWrapper.isUsingWriter()) {
            response_data = new String(response_data, "UTF-8")
                    .getBytes(httpResponseWrapper.getCharacterEncoding());
        }
        String response_content = new String(response_data, httpResponseWrapper
                .getCharacterEncoding());
        passResponse = !checkHtml.check_html(fullURL, response_content);
        if (passResponse) {
            System.out.println("passResponse:" + fullURL);
            OutputStream out = response.getOutputStream();// 二进制处理所有类型
            out.write(response_data);
            out.close();
        } else {
            System.out.println("can't passResponse:" + fullURL);
            sendErrorPage(httpRequestWrapper,
                    (HttpServletResponse) httpResponseWrapper.getResponse());
        } 
在$TOMCAT_HOME/conf/web.xml配置上面的filter,完了测试了下,上传文件处理超过16M文件时,新建buffer数组可能会报outofmemery错误


只有注册用户登录后才能发表评论。


网站导航: