欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

為什么SpringMVC中請(qǐng)求的body不支持多次讀取

 更新時(shí)間:2019年12月31日 14:14:28   作者:2的32次方  
這篇文章主要介紹了為什么SpringMVC中請(qǐng)求的body不支持多次讀取,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

在Springboot的項(xiàng)目中使用Servlet的Filter來實(shí)現(xiàn)方法簽名時(shí),發(fā)現(xiàn)請(qǐng)求的body不支持多次讀取。我是通過getInputStream()來獲取流,然后通過讀取流來獲取請(qǐng)求的body。

雖然網(wǎng)上有很多解決方案的例子,但是我發(fā)現(xiàn)沒有一篇文章解釋為什么會(huì)這樣的文章,所以決定自己去研究源碼。

問題表現(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沒有了,所以才會(huì)拋出這個(gè)異常。但是為什么body會(huì)沒有了呢?是否因?yàn)橥ㄟ^getInputStream()獲取到的流被讀取了所以引起這個(gè)問題呢?

復(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í)是通過調(diào)用AbstractMessageConverterMethodArgumentResolver的內(nèi)部類EmptyBodyCheckingHttpInputMessage的構(gòu)造方法來獲取流。

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表示流無數(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ì)通過分析Jetty應(yīng)用服務(wù)器對(duì)InputStream的實(shí)現(xiàn)來進(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)。所以問題應(yīng)該是由于HttpInput流重復(fù)讀取會(huì)直接返回-1引起的。這里不做展開,有興趣的朋友可以自行跟蹤源碼的運(yùn)行

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論