爲何SpringMVC中請求的body不支持屢次讀取

前言

Springboot的項目中使用ServletFilter來實現方法簽名時,發現請求的body不支持屢次讀取。我是經過getInputStream()來獲取流,而後經過讀取流來獲取請求的bodyweb

雖然網上有不少解決方案的例子,可是我發現沒有一篇文章解釋爲何會這樣的文章,因此決定本身去研究源碼。spring

問題表現

Content-Typeapplication/jsonPOST請求時,會返回狀態碼爲400的響應,響應的body以下:json

{
    "timestamp": "2019-12-27T02:48:50.544+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Required request body is missing: ...省略非關鍵信息...",
    "path": "/"
}

而在日誌中則有如下關鍵日誌服務器

2019-12-27 10:48:50.543  WARN 18352 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException:...省略非關鍵信息...

初步分析

根據提示信息能夠得知,因爲請求的body沒有了,因此纔會拋出這個異常。可是爲何body會沒有了呢?是否由於經過getInputStream()獲取到的流被讀取了因此引發這個問題呢?app

覆盤代碼

因而我編寫了一個覆盤的示例,就是一個在日誌中打印請求bodyFilter,關鍵代碼以下:eclipse

@Slf4j
@WebFilter
public class InputStreamFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        ServletInputStream inputStream=servletRequest.getInputStream();
        String charSetStr = servletRequest.getCharacterEncoding();
        if (charSetStr == null) {
            charSetStr = "UTF-8";
        }
        Charset charSet = Charset.forName(charSetStr);
        log.info("請求的body爲:\n{}",StreamUtils.copyToString(inputStream,charSet));
        filterChain.doFilter(servletRequest,servletResponse);
    }

RequestResponseBodyMethodProcessor

首先是找出拋出HttpMessageNotReadableException的方法和對應的類,關鍵類爲RequestResponseBodyMethodProcessorreadWithMessageConverters()方法:ide

@Override
    protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter,
            Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
        ...省略非關鍵代碼...
        // 關鍵代碼
        Object arg = readWithMessageConverters(inputMessage, parameter, paramType);
        if (arg == null && checkRequired(parameter)) {
            throw new HttpMessageNotReadableException("Required request body is missing: " +
                    parameter.getExecutable().toGenericString(), inputMessage);
        }
        return arg;
    }

從上面的代碼能夠得知,異常是因爲readWithMessageConverters()方法返回null且這個參數是必填引發,如今主要關注爲何返回null。因此查看readWithMessageConverters()方法ui

AbstractMessageConverterMethodArgumentResolver

而實際上實際上是調用了AbstractMessageConverterMethodArgumentResolverreadWithMessageConverters()方法,而在這個方法中實際上是經過調用AbstractMessageConverterMethodArgumentResolver的內部類EmptyBodyCheckingHttpInputMessage的構造方法來獲取流。this

readWithMessageConverters()關鍵代碼以下:日誌

@Nullable
    protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
            Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
        ...省略非關鍵代碼...
        EmptyBodyCheckingHttpInputMessage message;
        try {
            // 此處調用構造方法時進行了流的讀取
            message = new EmptyBodyCheckingHttpInputMessage(inputMessage);
            for (HttpMessageConverter<?> converter : this.messageConverters) {
                Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
                GenericHttpMessageConverter<?> genericConverter =
                        (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
                if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
                        (targetClass != null && converter.canRead(targetClass, contentType))) {
                    if (message.hasBody()) {
                        ...省略非關鍵代碼...
                    }
                    else {
                        // 此處是處理流讀取返回null的狀況
                        body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
                    }
                    break;
                }
            }
        }
        catch (IOException ex) {
            throw new HttpMessageNotReadableException("I/O error while reading input message", ex, inputMessage);
        }

        ...省略非關鍵代碼...

        MediaType selectedContentType = contentType;
        Object theBody = body;
        LogFormatUtils.traceDebug(logger, traceOn -> {
            String formatted = LogFormatUtils.formatValue(theBody, !traceOn);
            return "Read \"" + selectedContentType + "\" to [" + formatted + "]";
        });

        return body;
    }

EmptyBodyCheckingHttpInputMessage關鍵構造方法以下:

// 從請求中獲取到的InputStream對象
        @Nullable
        private final InputStream body;

        public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
            this.headers = inputMessage.getHeaders();
            InputStream inputStream = inputMessage.getBody();
            // 判斷InputStream是否支持mark
            if (inputStream.markSupported()) {
                // 標記流的起始位置
                inputStream.mark(1);
                // 讀取流
                this.body = (inputStream.read() != -1 ? inputStream : null);
                // 重置流,下次讀取會從起始位置從新開始讀取
                inputStream.reset();
            }
            else {
                // 回退輸入流,支持重複讀取的InputStream
                PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
                // 讀取流
                int b = pushbackInputStream.read();
                if (b == -1) {
                    // 返回-1表示流無數據存在
                    this.body = null;
                }
                else {
                    // 流存在數據,直接賦值
                    this.body = pushbackInputStream;
                    // 回退流到起始位置,等價於reset()方法
                    pushbackInputStream.unread(b);
                }
            }
        }

從上面的代碼能夠得知,起始SpringMVC是支持對請求的InputStream進行屢次讀取的以及InputStream其實能夠支持流重複讀取。可是實際上卻出現不支持流重複讀取的狀況,這是爲何呢?

下面會經過分析Jetty應用服務器對InputStream的實現來進行分析。

HttpInput

Jetty中繼承InputStrean的類是org.eclipse.jetty.server.HttpInputOverHTTP,而關鍵的代碼在其父類HttpInput上。

首先HttpInput繼承了ServletInputStream(這個抽象類繼承了·InputStream抽象類),且並未重寫markSupported()方法(這個方法默認實現爲返回false)。因此問題應該是因爲HttpInput流重複讀取會直接返回-1引發的。這裏不作展開,有興趣的朋友能夠自行跟蹤源碼的運行

相關文章
相關標籤/搜索