在用reset接口的時候,經常會使用request.getInputStream()方法,可是流只能讀取一次,一旦想要加上一個過濾器用來檢測用戶請求的數據時就會出現異常。html
重寫request的inputstream方法。。而後在須要部署應用中加上過濾器,在過濾器中加上這個重寫的request的方法web
以下:編寫filter並在web.xml中配置filter數組
@WebFilter(filterName="accessFilter", urlPatterns={ "*.do", // "*.jsp", // "/*", // "/layout/*", // "/apply/*", // "/audit/*", // "/authority/*", // "/commonWare/*", // "/contract/*", // "/marketing/*", // "/product/*", // "/project/*", // "/system/*", // "/user/*" }) public class MyFilter implements Filter { // 日誌對象 private static Logger logger = Logger.getLogger(MyFilter.class); public void init(FilterConfig filterConfig) throws ServletException { } public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; System.out.println("=====+" + req.hashCode()); HttpServletResponse response = (HttpServletResponse) res; if ("POST".equalsIgnoreCase(request.getMethod())) { ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request); System.out.println("===filter==+" + requestWrapper.hashCode()); String body = HttpUtil.getBodyString(requestWrapper); System.out.println("AccessFilter="+body); chain.doFilter(requestWrapper, response); return ; } chain.doFilter(req, res); } }
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); body = HttpUtil.getBodyString(request).getBytes(Charset.forName("UTF-8")); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } }; } }
public static String getBodyString(ServletRequest request) { StringBuilder sb = new StringBuilder(); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = request.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
參考:https://www.cnblogs.com/a393060727/p/6141295.html緩存