怎么让request inputstream 可以多次读取
1、包装ServletRequest对象
public class IRequestWrapper extends HttpServletRequestWrapper { private byte[] body; public IRequestWrapper(HttpServletRequest request) throws IOException { super(request); body = readBytes(request.getInputStream()); } public static byte[] readBytes(InputStream is) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.flush(); return bos.toByteArray(); } @Override public BufferedReader getReader() { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() { return byteArrayInputStream.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } }; } }
2、在过滤器中应用包装
public class HttpServletRequestWrapperFilter implements Filter { @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { request = new IRequestWrapper((HttpServletRequest) request); } chain.doFilter(request, response); } @Override public void destroy() { } }
posted on 2021-06-25 16:00 mylittlecabin 阅读(236) 评论(0) 编辑 收藏 举报