過濾器應用【編碼、敏感詞、壓縮、轉義過濾器】

Java3y發表於2018-02-08

前言

在上篇博文中,我們已經講解了過濾器的基本概念,使用以及簡單的Servlet應用了。這篇博文主要講解過濾器的高階應用。。

編碼過濾器

目的:解決全站的亂碼問題

開發過濾器


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //將request和response強轉成http協議的
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

        httpServletRequest.setCharacterEncoding("UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=UTF-8");
        
        chain.doFilter(httpServletRequest, httpServletResponse);
    }

第一次測試

Servlet1中向瀏覽器回應中文資料,沒有出現亂碼。


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.getWriter().write("看完部落格點贊!");

    }

這裡寫圖片描述


分析

上面的過濾器是不完善的,因為瀏覽器用get方式提交給伺服器的中文資料,單單靠上面的過濾器是無法完成的!

那麼我們需要怎麼做呢??我們之前解決get方式的亂碼問題是這樣的:使用request獲取傳遞過來的資料,經過ISO 8859-1反編碼獲取得到不是亂碼的資料(傳到Servlet上的資料已經被ISO 8859-1編碼過了,反編碼就可以獲取原來的資料),再用UTF-8編碼,得到中文資料!

參考我之前的博文:https://mp.weixin.qq.com/s?__biz=MzI4Njg5MDA5NA==&mid=100000001&idx=6&sn=b0c346d7f17a097525ad106291aad28c&chksm=6bd740005ca0c916f72872122dff3bad8c49f9f690ea51b442b542dbbb654382bb663a01473b&mpshare=1&scene=1&srcid=0206hvswcHK67to1b4tr46AK#rd

在Servlet獲取瀏覽器以GET方式提交過來的中文是亂碼的根本原因是:getParameter()方法是以ISO 8859-1的編碼來獲取瀏覽器傳遞過來的資料的,得到的是亂碼

既然知道了根本原因,那也好辦了:過濾器傳遞的request物件,使用getParameter()方法的時候,獲取得到的是正常的中文資料

也就是說,sun公司為我們提供的request物件是不夠用的,因為sun公司提供的request物件使用getParameter()獲取get方式提交過來的資料是亂碼,於是我們要增強request物件(使得getParameter()獲取得到的是中文)!

增強request物件

增強request物件,我們要使用包裝設計模式!

包裝設計模式的五個步驟:

  • 1、實現與被增強物件相同的介面
  • 2、定義一個變數記住被增強物件
  • 3、定義一個構造器,接收被增強物件
  • 4、覆蓋需要增強的方法
  • 5、對於不想增強的方法,直接呼叫被增強物件(目標物件)的方法

sun公司也知道我們可能對request物件的方法不滿意,於是提供了HttpServletRequestWrapper類給我們實現(如果實現HttpServletRequest介面的話,要實現太多的方法了!)



    class MyRequest extends HttpServletRequestWrapper {
    
        private HttpServletRequest request;
    
        public MyRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }
    
        @Override
        public String getParameter(String name) {
            String value = this.request.getParameter(name);
    
            if (value == null) {
                return null;
            }
    
            //如果不是get方法的,直接返回就行了
            if (!this.request.getMethod().equalsIgnoreCase("get")) {
                return value;
            }
    
            try {
    
                //進來了就說明是get方法,把亂碼的資料
                value = new String(value.getBytes("ISO8859-1"), this.request.getCharacterEncoding());
                return value ;
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
    
                throw new RuntimeException("不支援該編碼");
            }
    
        }
    }

將被增強的request物件傳遞給目標資源,那麼目標資源使用request呼叫getParameter()方法的時候,獲取得到的就是中文資料,而不是亂碼了!


        //將request和response強轉成http協議的
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

        httpServletRequest.setCharacterEncoding("UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=UTF-8");

        MyRequest myRequest = new MyRequest(httpServletRequest);

        //傳遞給目標資源的request是被增強後的。
        chain.doFilter(myRequest, httpServletResponse);

第二次測試

  • 使用get方式傳遞中文資料給伺服器

<form action="${pageContext.request.contextPath}/Servlet1" method="get">

    <input type="hidden" name="username" value="中國">
    

    <input type="submit" value="提交">
</form>

這裡寫圖片描述


敏感詞的過濾器

如果使用者輸入了敏感詞(傻b、尼瑪、操蛋等等不文明語言時),我們要將這些不文明用於遮蔽掉,替換成符號!

要實現這樣的功能也很簡單,使用者輸入的敏感詞肯定是在getParameter()獲取的,我們在getParameter()得到這些資料的時候,判斷有沒有敏感詞彙,如果有就替換掉就好了!簡單來說:也是要增強request物件

增強request物件


    class MyDirtyRequest extends HttpServletRequestWrapper {
    
        HttpServletRequest request;
    
        //定義一堆敏感詞彙
        private List<String> list = Arrays.asList("傻b", "尼瑪", "操蛋");
    
        public MyDirtyRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }
    
        @Override
        public String getParameter(String name) {
    
            String value = this.request.getParameter(name);
    
            if (value == null) {
                return null;
            }
    
            //遍歷list集合,看看獲取得到的資料有沒有敏感詞彙
            for (String s : list) {
    
                if (s.equals(value)) {
                    value = "*****";
                }
            }
    
            return value ;
        }
    }

開發過濾器


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //將request和response強轉成http協議的
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

        MyDirtyRequest dirtyRequest = new MyDirtyRequest(httpServletRequest);

        //傳送給目標資源的是被增強後的request物件
        chain.doFilter(dirtyRequest, httpServletResponse);
    }

測試

這裡寫圖片描述


壓縮資源過濾器

按照過濾器的執行順序:執行完目標資源,過濾器後面的程式碼還會執行。所以,我們在過濾器中可以獲取執行完目標資源後的response物件!

我們知道sun公司提供的response物件呼叫write()方法,是直接把資料返回給瀏覽器的。我們要想實現壓縮的功能,write()方法就不能直接把資料寫到瀏覽器上!

這和上面是類似的,過濾器傳遞給目標資源的response物件就需要被我們增強,使得目標資源呼叫writer()方法的時候不把資料直接寫到瀏覽器上

增強response物件

response物件可能會使用PrintWriter或者ServletOutputStream物件來呼叫writer()方法的,所以我們增強response物件的時候,需要把getOutputSteam和getWriter()重寫

    
    class MyResponse extends HttpServletResponseWrapper{
    
        HttpServletResponse response;
        public MyResponse(HttpServletResponse response) {
            super(response);
            this.response = response;
        }
    
    
        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            return super.getOutputStream();
        }
    
        @Override
        public PrintWriter getWriter() throws IOException {
            return super.getWriter();
        }
    }

接下來,ServletOutputSteam要呼叫writer()方法,使得它不會把資料寫到瀏覽器上。這又要我們增強一遍了!

增強ServletOutputSteam


    /*增強ServletOutputSteam,讓writer方法不把資料直接返回給瀏覽器*/
    class MyServletOutputStream extends ServletOutputStream{
    
        private ByteArrayOutputStream byteArrayOutputStream;
    
        public MyServletOutputStream(ByteArrayOutputStream byteArrayOutputStream) {
            this.byteArrayOutputStream = byteArrayOutputStream;
        }
    
        //當呼叫write()方法的時候,其實是把資料寫byteArrayOutputSteam上
        @Override
        public void write(int b) throws IOException {
            this.byteArrayOutputStream.write(b);
    
        }
    }

增強PrintWriter

PrintWriter物件就好辦了,它本來就是一個包裝類,看它的構造方法,我們直接可以把ByteArrayOutputSteam傳遞給PrintWriter上。

這裡寫圖片描述


    @Override
    public PrintWriter getWriter() throws IOException {
        printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream, this.response.getCharacterEncoding()));

        return printWriter;
    }

獲取快取資料

我們把資料都寫在了ByteArrayOutputSteam上了,應該提供方法給外界過去快取中的資料!


    public byte[] getBuffer() {

        try {

            //防止資料在快取中,要重新整理一下!
            if (printWriter != null) {
                printWriter.close();
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.flush();
                return byteArrayOutputStream.toByteArray();
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

增強response的完整程式碼


class MyResponse extends HttpServletResponseWrapper{

    private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    private PrintWriter printWriter ;

    private HttpServletResponse response;
    public MyResponse(HttpServletResponse response) {
        super(response);
        this.response = response;
    }


    @Override
    public ServletOutputStream getOutputStream() throws IOException {

        //這個的ServletOutputSteam物件呼叫write()方法的時候,把資料是寫在byteArrayOutputSteam上的
        return new MyServletOutputStream(byteArrayOutputStream);
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream, this.response.getCharacterEncoding()));

        return printWriter;
    }

    public byte[] getBuffer() {

        try {

            //防止資料在快取中,要重新整理一下!
            if (printWriter != null) {
                printWriter.close();
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.flush();
                return byteArrayOutputStream.toByteArray();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

過濾器


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {


        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        MyResponse myResponse = new MyResponse(response);

        //把被增強的response物件傳遞進去,目標資源呼叫write()方法的時候就不會直接把資料寫在瀏覽器上了
        chain.doFilter(request, myResponse);

        //得到目標資源想要返回給瀏覽器的資料
        byte[] bytes = myResponse.getBuffer();

        //輸出原來的大小
        System.out.println("壓縮前:"+bytes.length);

        
        //使用GZIP來壓縮資源,再返回給瀏覽器
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(bytes);
        gzipOutputStream.flush();
        
        //得到壓縮後的資料
        byte[] gzip = byteArrayOutputStream.toByteArray();
        
        System.out.println("壓縮後:" + gzip.length);
        
        //還要設定頭,告訴瀏覽器,這是壓縮資料!
        response.setHeader("content-encoding", "gzip");
        response.setContentLength(gzip.length);
        response.getOutputStream().write(gzip);
     
    }

測試

  • 在Servlet上輸出一大段文字:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.getWriter().write("fdshfidsuhfidusfhuidsfhuidshdsuifhsd" +
                "uifhsduifffffdshfidsuhfidusfhuidsfhuidshdsuif" +
                "hsduifhsduifffffdshfidsuhfidusfhuidsfhuidshd" +
                "suifhsduifhsduifffffdshfidsuhfidusfhuidsfhuidsh" +
                "dsuifhsduifhsduifffffdshfidsuhfidusfhuidsfhuids" +
                "hdsuifhsduifhsduifffffdshfidsuhfidusfhuidsfhuid" +
                "shdsuifhsduifhsduiffdshfidsuhfidusfhuidsfhuids" +
                "hdsuifhsduifhsduifffffdshfidsuhfidusfhuidsfhui" +
                "dshdsuifhsduifhsduifffffdshfidsuhfidusfhuidsfh" +
                "uidshdsuifhsduifhsduifffffdshfidsuhfidusfhuids" +
                "fhuidshdsuifhsduifhsduifffffdshfidsuhfidusfhuid" +
                "sfhuidshdsuifhsduifhsduifffffdshfidsuhfidusfhui" +
                "dsfhuidshdsuifhsduifhsduifffffdshfidsuhfidusfh" +
                "uidsfhuidshdsuifhsduifhsduifffffdshfidsuhfidusf" +
                "huidsfhuidshdsuifhsduifhsduifffffdshfidsuhfidus" +
                "fhuidsfhuidshdsuifhsduifhsduifffffdshfidsuhfid" +
                "usfhuidsfhuidshdsuifhsduifhsduifffffdshfidsuhf" +
                "idusfhuidsfhuidshdsuifhsduifhsd" +
                "uifffffdshfidsuhfidusfhuidsfhuidshdsuifhsduifhsduifffffff");

    }
  • 效果:

這裡寫圖片描述


HTML轉義過濾器

只要把getParameter()獲取得到的資料轉義一遍,就可以完成功能了。

增強request



class MyHtmlRequest extends HttpServletRequestWrapper{

    private HttpServletRequest request;

    public MyHtmlRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }


    @Override
    public String getParameter(String name) {

        String value = this.request.getParameter(name);
        return this.Filter(value);
        
    }

    public String Filter(String message) {
        if (message == null)
            return (null);

        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case `<`:
                    result.append("&lt;");
                    break;
                case `>`:
                    result.append("&gt;");
                    break;
                case `&`:
                    result.append("&amp;");
                    break;
                case `"`:
                    result.append("&quot;");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
        
    }
    
}

過濾器





    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {



        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        MyHtmlRequest myHtmlRequest = new MyHtmlRequest(request);

        //傳入的是被增強的request!
        chain.doFilter(myHtmlRequest, response);

    }

測試

jsp程式碼:


    <form action="${pageContext.request.contextPath}/Servlet1" method="post">
    
    
        <input type="hidden" name="username" value="<h1>你好i好<h1>">
    
        <input type="submit" value="提交">
    </form>

Servlet程式碼:


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String value = request.getParameter("username");
        response.getWriter().write(value);

    }

這裡寫圖片描述


快取資料到記憶體中

在前面我們已經做過了,讓瀏覽器不快取資料【驗證碼的圖片是不應該快取的】。

現在我們要做的是:快取資料到記憶體中【如果某個資源重複使用,不輕易變化,應該快取到記憶體中】

這個和壓縮資料的Filter非常類似的,因為讓資料不直接輸出給瀏覽器,把資料用一個容器(ByteArrayOutputSteam)存起來。如果已經有快取了,就取快取的。沒有快取就執行目標資源!

增強response物件

class MyResponse extends HttpServletResponseWrapper {

    private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    private PrintWriter printWriter ;

    private HttpServletResponse response;
    public MyResponse(HttpServletResponse response) {
        super(response);
        this.response = response;
    }


    @Override
    public ServletOutputStream getOutputStream() throws IOException {

        //這個的ServletOutputSteam物件呼叫write()方法的時候,把資料是寫在byteArrayOutputSteam上的
        return new MyServletOutputStream(byteArrayOutputStream);
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream, this.response.getCharacterEncoding()));

        return printWriter;
    }

    public byte[] getBuffer() {

        try {

            //防止資料在快取中,要重新整理一下!
            if (printWriter != null) {
                printWriter.close();
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.flush();
                return byteArrayOutputStream.toByteArray();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


//增強ServletOutputSteam,讓writer方法不把資料直接返回給瀏覽器

class MyServletOutputStream extends ServletOutputStream {

    private ByteArrayOutputStream byteArrayOutputStream;

    public MyServletOutputStream(ByteArrayOutputStream byteArrayOutputStream) {
        this.byteArrayOutputStream = byteArrayOutputStream;
    }

    //當呼叫write()方法的時候,其實是把資料寫byteArrayOutputSteam上
    @Override
    public void write(int b) throws IOException {
        this.byteArrayOutputStream.write(b);

    }
}

過濾器



    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //定義一個Map集合,key為頁面的地址,value為記憶體的快取
        Map<String, byte[]> map = new HashMap<>();

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //得到客戶端想要請求的資源
        String uri = request.getRequestURI();
        byte[] bytes = map.get(uri);

        //如果有快取,直接返回給瀏覽器就行了,就不用執行目標資源了
        if (bytes != null) {
            response.getOutputStream().write(bytes);
            return ;
        }

        //如果沒有快取,就讓目標執行
        MyResponse myResponse = new MyResponse(response);
        chain.doFilter(request, myResponse);

        //得到目標資源想要傳送給瀏覽器的資料
        byte[] b = myResponse.getBuffer();

        //把資料存到集合中
        map.put(uri, b);

        //把資料返回給瀏覽器
        response.getOutputStream().write(b);


    }

測試

儘管是重新整理,獲取得到的也是從快取拿到的資料!

這裡寫圖片描述


如果文章有錯的地方歡迎指正,大家互相交流。習慣在微信看技術文章的同學,可以關注微信公眾號:Java3y

相關文章