标签:就是 并且 介绍 project super pos cep ide trace
在用reset接口的时候,常常会使用request.getInputStream()方法,但是流只能读取一次,一旦想要加上一个过滤器用来检测用户请求的数据时就会出现异常。
重写request的inputstream方法。。然后在需要部署应用中加上过滤器,在过滤器中加上这个重写的request的方法
如下:编写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
标签:就是 并且 介绍 project super pos cep ide trace
原文地址:https://www.cnblogs.com/flgb/p/10976751.html