1. 程式人生 > >SpringBoot攔截器或過濾器中使用流讀取引數後,controller中註解讀取不到引數

SpringBoot攔截器或過濾器中使用流讀取引數後,controller中註解讀取不到引數

今天出現這樣一個問題:
現在開發的專案是基於SpringBoot的maven專案,有個需求就是要加一個攔截器和過濾器,在攔截器中我需要獲取到前端傳過來的json資料,按照常理來說,獲取請求引數使用request.getParameter()方法就可以,但是不知道為什麼在這個專案裡面獲取不到。這時候我想到了使用流的方法從request物件中直接讀出來。
當然,方法寫好後,在攔截器中也讀取到了請求引數,但是出現一個問題。就是後面的controller中使用了@RequestBody註解獲取引數,但是攔截器執行過後,controller獲取不到引數,甚至是方法都沒有進入對應的方法中就報錯了(注:攔截器中不使用流,controller中是能獲取到引數的)。
在debug過程中,發現攔截器使用流和不適用流到了一個獲取字符集解析器的方法裡面就有差別了。一個是能獲取到字符集解析器。另一個獲取不到。但是看了執行過程也沒發現什麼問題。就百度了一下,發現了Spring有一個問題就是: ServletRequest中getReader()和getInputStream()只能呼叫一次。而又由於@RequestBody註解獲取輸出引數的方式也是根據流的方式獲取的。所以我們前面使用流獲取後,後面的@RequestBody就獲取不到對應的輸入流了。
那麼問題找到之後。想著解決。從網上查找了一下,有一個方法就是。先讀取流,然後在將流寫進去就行了,下面是我的一些解決程式碼:
過濾器:

package com.***;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * Created by yefuliang on 2017/10/25.
 */
@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter  implements Filter {
    @Override
public void init(FilterConfig filterConfig) throws ServletException { System.out.println("--------------過濾器初始化------------"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("--------------執行過濾操作------------"
); // 防止流讀取一次後就沒有了, 所以需要將流繼續寫出去 HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest); filterChain.doFilter(requestWrapper, servletResponse); } @Override public void destroy() { System.out.println("--------------過濾器銷燬------------"); } }

在程式碼中我們可以看到我們為了方式流的丟失,我們新建了一個類的物件,注意filterChain.doFilter(requestWrapper, servletResponse);這句程式碼的requestWrapper引數,和原生的不一致哦,是我們處理過後的ServletRequest。下面是BodyReaderHttpServletRequestWrapper的實現:

package com.***;

/**
 * Created by yefuliang on 2017/10/25.
 */

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

/**
 * 儲存流
 *
 * @author yefuliang 2017年10月25日
 */
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        String sessionStream = getBodyString(request);
        body = sessionStream.getBytes(Charset.forName("UTF-8"));
    }

    /**
     * 獲取請求Body
     *
     * @param request
     * @return
     */
    public String getBodyString(final ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = cloneInputStream(request.getInputStream());
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * Description: 複製輸入流</br>
     *
     * @param inputStream
     * @return</br>
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byteArrayInputStream;
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

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

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}

程式碼邏輯大家可以自己看下,很簡單的一個邏輯。
下面是我的攔截器獲取引數程式碼:

package com.***;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.UUID;

/**
 * 自定義攔截器
 * 攔截時機 Filter pre -> service -> dispatcher -> preHandle ->controller
 *  ->postHandle - > afterCompletion -> FilterAfter
 * Created by yefuliang on 2017/10/23.
 */
public class bgqCommonInterceptorl implements HandlerInterceptor {

    /**
     * 在controller處理之前首先對請求引數進行處理,以及對公共引數的儲存
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("---------------攔截器開始------------------");
        try{
            response.setHeader("Content-type", "application/json;charset=UTF-8");

            String requestMethord = request.getRequestURI();//請求方法
            if(requestMethord==null){
                return false;
            }

            //獲取請求引數
            JSONObject parameterMap = JSON.parseObject(new BodyReaderHttpServletRequestWrapper(request).getBodyString(request));
            String dataFrom = String.valueOf(parameterMap.get("dataFrom")); 

        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("攔截器攔截完成");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("---------------攔截器方法二開始------------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("---------------攔截器方法三開始------------------");
    }

parameterMap 就是獲取的請求引數json物件。
問題解決。