為什么SpringMVC中請(qǐng)求的body不支持多次讀取
前言
在Springboot的項(xiàng)目中使用Servlet的Filter來(lái)實(shí)現(xiàn)方法簽名時(shí),發(fā)現(xiàn)請(qǐng)求的body不支持多次讀取。我是通過(guò)getInputStream()來(lái)獲取流,然后通過(guò)讀取流來(lái)獲取請(qǐng)求的body。
雖然網(wǎng)上有很多解決方案的例子,但是我發(fā)現(xiàn)沒(méi)有一篇文章解釋為什么會(huì)這樣的文章,所以決定自己去研究源碼。
問(wèn)題表現(xiàn)
Content-Type為application/json的POST請(qǐng)求時(shí),會(huì)返回狀態(tài)碼為400的響應(yīng),響應(yīng)的body如下:
{ "timestamp": "2019-12-27T02:48:50.544+0000", "status": 400, "error": "Bad Request", "message": "Required request body is missing: ...省略非關(guān)鍵信息...", "path": "/" }
而在日志中則有以下關(guān)鍵日志
2019-12-27 10:48:50.543 WARN 18352 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException:...省略非關(guān)鍵信息...
初步分析
根據(jù)提示信息可以得知,由于請(qǐng)求的body沒(méi)有了,所以才會(huì)拋出這個(gè)異常。但是為什么body會(huì)沒(méi)有了呢?是否因?yàn)橥ㄟ^(guò)getInputStream()獲取到的流被讀取了所以引起這個(gè)問(wèn)題呢?
復(fù)盤代碼
于是我編寫了一個(gè)復(fù)盤的示例,就是一個(gè)在日志中打印請(qǐng)求body的Filter,關(guān)鍵代碼如下:
@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("請(qǐng)求的body為:\n{}",StreamUtils.copyToString(inputStream,charSet)); filterChain.doFilter(servletRequest,servletResponse); }
RequestResponseBodyMethodProcessor
首先是找出拋出HttpMessageNotReadableException的方法和對(duì)應(yīng)的類,關(guān)鍵類為RequestResponseBodyMethodProcessor的readWithMessageConverters()方法:
@Override protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter, Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { ...省略非關(guān)鍵代碼... // 關(guān)鍵代碼 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且這個(gè)參數(shù)是必填引起,現(xiàn)在主要關(guān)注為什么返回null。所以查看readWithMessageConverters()方法
AbstractMessageConverterMethodArgumentResolver
而實(shí)際上其實(shí)是調(diào)用了AbstractMessageConverterMethodArgumentResolver的readWithMessageConverters()方法,而在這個(gè)方法中其實(shí)是通過(guò)調(diào)用AbstractMessageConverterMethodArgumentResolver的內(nèi)部類EmptyBodyCheckingHttpInputMessage的構(gòu)造方法來(lái)獲取流。
readWithMessageConverters()關(guān)鍵代碼如下:
@Nullable protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { ...省略非關(guān)鍵代碼... EmptyBodyCheckingHttpInputMessage message; try { // 此處調(diào)用構(gòu)造方法時(shí)進(jìn)行了流的讀取 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()) { ...省略非關(guān)鍵代碼... } 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); } ...省略非關(guān)鍵代碼... MediaType selectedContentType = contentType; Object theBody = body; LogFormatUtils.traceDebug(logger, traceOn -> { String formatted = LogFormatUtils.formatValue(theBody, !traceOn); return "Read \"" + selectedContentType + "\" to [" + formatted + "]"; }); return body; }
EmptyBodyCheckingHttpInputMessage關(guān)鍵構(gòu)造方法如下:
// 從請(qǐng)求中獲取到的InputStream對(duì)象 @Nullable private final InputStream body; public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException { this.headers = inputMessage.getHeaders(); InputStream inputStream = inputMessage.getBody(); // 判斷InputStream是否支持mark if (inputStream.markSupported()) { // 標(biāo)記流的起始位置 inputStream.mark(1); // 讀取流 this.body = (inputStream.read() != -1 ? inputStream : null); // 重置流,下次讀取會(huì)從起始位置重新開始讀取 inputStream.reset(); } else { // 回退輸入流,支持重復(fù)讀取的InputStream PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream); // 讀取流 int b = pushbackInputStream.read(); if (b == -1) { // 返回-1表示流無(wú)數(shù)據(jù)存在 this.body = null; } else { // 流存在數(shù)據(jù),直接賦值 this.body = pushbackInputStream; // 回退流到起始位置,等價(jià)于reset()方法 pushbackInputStream.unread(b); } } }
從上面的代碼可以得知,起始SpringMVC是支持對(duì)請(qǐng)求的InputStream進(jìn)行多次讀取的以及InputStream其實(shí)可以支持流重復(fù)讀取。但是實(shí)際上卻出現(xiàn)不支持流重復(fù)讀取的情況,這是為什么呢?
下面會(huì)通過(guò)分析Jetty應(yīng)用服務(wù)器對(duì)InputStream的實(shí)現(xiàn)來(lái)進(jìn)行分析。
HttpInput
Jetty中繼承InputStrean的類是org.eclipse.jetty.server.HttpInputOverHTTP,而關(guān)鍵的代碼在其父類HttpInput上。
首先HttpInput繼承了ServletInputStream(這個(gè)抽象類繼承了·InputStream抽象類),且并未重寫markSupported()方法(這個(gè)方法默認(rèn)實(shí)現(xiàn)為返回false)。所以問(wèn)題應(yīng)該是由于HttpInput流重復(fù)讀取會(huì)直接返回-1引起的。這里不做展開,有興趣的朋友可以自行跟蹤源碼的運(yùn)行
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
欄 目:Java
下一篇:java常用數(shù)據(jù)流應(yīng)用實(shí)例解析
本文標(biāo)題:為什么SpringMVC中請(qǐng)求的body不支持多次讀取
本文地址:http://mengdiqiu.com.cn/a1/Java/8785.html
您可能感興趣的文章
- 01-10Springboot中@Value的使用詳解
- 01-10淺談Java中真的只有值傳遞么
- 01-10Java搭建RabbitMq消息中間件過(guò)程詳解
- 01-10springmvc級(jí)聯(lián)屬性處理無(wú)法轉(zhuǎn)換異常問(wèn)題解決
- 01-10mybatis if標(biāo)簽使用總結(jié)
- 01-10簡(jiǎn)單了解Spring中BeanFactory與FactoryBean的區(qū)別
- 01-10java中的String定義的字面量最大長(zhǎng)度是多少
- 01-10java中堆內(nèi)存與棧內(nèi)存的知識(shí)點(diǎn)總結(jié)
- 01-10java中接口和事件監(jiān)聽器的深入理解
- 01-10SpringBoot中的五種對(duì)靜態(tài)資源的映射規(guī)則的實(shí)現(xiàn)


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10Java實(shí)現(xiàn)動(dòng)態(tài)模擬時(shí)鐘
- 01-10Springboot中@Value的使用詳解
- 01-10JavaWeb實(shí)現(xiàn)郵件發(fā)送功能
- 01-10利用Java實(shí)現(xiàn)復(fù)制Excel工作表功能
- 01-10Java實(shí)現(xiàn)動(dòng)態(tài)數(shù)字時(shí)鐘
- 01-10java基于poi導(dǎo)出excel透視表代碼實(shí)例
- 01-10java實(shí)現(xiàn)液晶數(shù)字字體顯示當(dāng)前時(shí)間
- 01-10基于Java驗(yàn)證jwt token代碼實(shí)例
- 01-10Java動(dòng)態(tài)顯示當(dāng)前日期和時(shí)間
- 01-10淺談Java中真的只有值傳遞么
隨機(jī)閱讀
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文