首頁 > Java > java教程 > 如何無消耗地多次存取HTTP Servlet請求參數?

如何無消耗地多次存取HTTP Servlet請求參數?

DDD
發布: 2024-11-30 10:15:19
原創
480 人瀏覽過

How to Access HTTP Servlet Request Parameters Multiple Times Without Consumption?

無消耗存取HTTP Servlet請求參數

問題:

問題:

問題:

public class MultiReadHttpServletRequest extends HttpServletRequestWrapper { private ByteArrayOutputStream cachedBytes; public MultiReadHttpServletRequest(HttpServletRequest request) { super(request); } @Override public ServletInputStream getInputStream() throws IOException { if (cachedBytes == null) cacheInputStream(); return new CachedServletInputStream(cachedBytes.toByteArray()); } @Override public BufferedReader getReader() throws IOException{ return new BufferedReader(new InputStreamReader(getInputStream())); } private void cacheInputStream() throws IOException { cachedBytes = new ByteArrayOutputStream(); IOUtils.copy(super.getInputStream(), cachedBytes); } private static class CachedServletInputStream extends ServletInputStream { private final ByteArrayInputStream buffer; public CachedServletInputStream(byte[] contents) { this.buffer = new ByteArrayInputStream(contents); } @Override public int read() { return buffer.read(); } // ... Implementation for newer versions of ServletInputStream interface } }

解決方案:
public class MyFilter implements Filter {
  public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);
    doMyThing(multiReadRequest.getInputStream());
    chain.doFilter(multiReadRequest, response);
  }
}
登入後複製
要存取參數而不消耗它們,您可以擴展HttpServletRequestWrapper 並實作自訂方法快取輸入流:透過使用此類包裝原始請求,您可以存取在過濾器鏈內外多次快取輸入流,允許getParameterXXX 和doMyThing 等自訂方法讀取參數:

以上是如何無消耗地多次存取HTTP Servlet請求參數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板